# -*- coding:utf-8 -*-
from utils.views import AuthenticationExceptView, WdCreateAPIView, WdListCreateAPIView, WdRetrieveUpdateAPIView, \
    WdDestroyAPIView, WdListAPIView, WdAPIView, WdRetrieveAPIView
from utils.response import general_json_response, ErrorCode
from rest_framework import status, exceptions
from users.models import AuthUser, CompanyInfo, CompanyWebsiteInfo, Person, CompanyPerson, Records, CompanyAutoSubmit, \
     RoleBusinessPermission, AdminRole, BusinessPermission, Organization, OrganizationElevatorRelation, \
     OrganizationAdminRoRelation, ElevatorAdminRoRelation, AuthUserElevatorRelation, BasicSupervisedRelation, \
    LogRefresh, SystemLog
from django.contrib.auth.hashers import make_password
from utils.logger import get_logger
from serializer import AuthUserSerializer, CompanySerializer, CompanyListSerializer, PersonSerializer, \
    PersonListSerializer, CompanyListSerializerV2, CompanyPersonListSerializer, CompanyPersonSerializer,\
    RecordsListSerializer, PersonBindListSerializer, AdminRoleSerializer, \
    OrganizationSerializer, OrganizationElevatorRelationSerializer, ElevatorSerializer, CompanyForAuthUserSerializer, \
    AuthUserListSerializer, SystemLogSerializer
from django.contrib.auth import login, authenticate, logout
import json
from basic.models import ElevatorInfo, ElevatorPersonInfo
from maintenance.models import Contract
from django.db.models.signals import post_save, post_delete
from ElevatorAdmin.tasks import test_for_celery
from django.db import IntegrityError
from ElevatorAdmin import settings
import os
import random
import string
import operator
from datetime import datetime, date, timedelta
from datetime import timedelta, date
from data_import import data_import
import re
from basic.models import ElevatorPersonInfo
from utils import piccode, mysql_singleton
from utils import get_random_char, get_random_char_list
import redis
import uuid
from rest_framework.renderers import TemplateHTMLRenderer
from utils.cryptor import AESCrypto
from ElevatorAdmin.settings import AES_KEY
from django.db.models import Max
import copy
from rest_framework.exceptions import NotFound
from django.db.models import F, Q
from ElevatorAdmin.settings import TO_GOV, platform_name, copyright, record_number, logo, logo_ico


logger = get_logger(__name__)


def get_permission(text):
    try:
        ao = AESCrypto(AES_KEY)
        p = ao.decrypt(text=text).split(",")
    except Exception as e:
        p = []
    return p


def get_ip(request):
    x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
    ip = x_forwarded_for.split(',')[-1].strip()
    return ip


def get_company_count(user):
    qs = CompanyInfo.objects.filter_active()

    if user.role == 20:
        qs = qs.filter(service_id=user.service_id)
        return qs.count()
    elif user.role == 30:
        return 1
    else:
        return qs.count()


def get_registers(user):
    u""" 非各个角色的管理员才会调用 """
    from users.models import OrganizationElevatorRelation, OrganizationAdminRoRelation, ElevatorAdminRoRelation, \
        AuthUserElevatorRelation
    if user.permission_type == 20:
        codes = AuthUserElevatorRelation.objects.filter_active(auth_user=user).values_list("register_code", flat=True).distinct()
        return codes
    admin_role = user.admin_role
    codes = list()
    if not admin_role:
        return codes
    if admin_role.management_type == 20:
        codes = ElevatorAdminRoRelation.objects.filter_active(admin_role=admin_role).values_list("register_code", flat=True).distinct()
        return codes
    oarr = OrganizationAdminRoRelation.objects.filter_active(admin_role=admin_role).first()
    if not oarr:
        return codes
    org = oarr.organization
    if not org:
        return codes
    codes = OrganizationElevatorRelation.objects.filter_active(organization=org).values_list("register_code", flat=True).distinct()
    return codes


def get_authority_count(user):
    # l = ElevatorInfo.objects.filter_active(~Q(manufacturer_company=None), ~Q(factory_no=None))
    from manufacturer.models import AuthorityCode
    l = ElevatorInfo.objects.filter_active(~Q(factory_no=''), manufacturer_company__isnull=False)
    if user.role == 0:
        pass
    elif user.role in (10, 20, 30, 40):
        if user.role == 10 or not user.company_person.is_admin:
            service_id = user.service_id
            l = l.filter(service_id=service_id)
            codes = get_registers(user)
            l = l.filter(register_code__in=codes)
        else:
            service_id = user.service_id
            l = l.filter(service_id=service_id)
    else:
        l = l.none()
    m = []
    for ei in l:
        m.append({"manufacturer_code": ei.manufacturer_company.code, "manufacturer_number": ei.factory_no})
    ids = []
    for dic in m:
        ac = AuthorityCode.objects.filter_active(manufacturer_code_elevator=dic['manufacturer_code'], manufacturer_number_elevator=dic['manufacturer_number']).first()
        if ac:
            ids.append(ac.id)
    return len(ids)


def get_user_info(request, user, context):
    from manufacturer.models import CompanyPlatform, ElevatorFault, AlarmMsg
    now = datetime.now()
    today = datetime(year=now.year, month=now.month, day=now.day)
    user_info = AuthUserSerializer(instance=user, many=False, context=context).data
    permissions = user.permissions()
    ao = AESCrypto(AES_KEY)
    request.session['ep'] = ao.encrypt(",".join(permissions))
    user_info['pt'] = get_permissions_tree(permissions, user.username)
    elevator_count = ElevatorInfo.objects.filter_active().count()
    access_count = CompanyPlatform.objects.count()
    today_fault = ElevatorFault.objects.filter_active(create_time__gte=today).count() + AlarmMsg.objects.filter_active(create_time__gte=today).values_list("authority_code_id", flat=True).distinct().count()
    user_info['elevator_count'] = elevator_count
    user_info['access_count'] = access_count
    user_info['today_fault'] = today_fault
    user_info['company_count'] = get_company_count(user)
    user_info['authority_count'] = get_authority_count(user)

    web = ''
    if user.role in [10, 20, 30, 40]:
        si = user.service_id
        ci = CompanyInfo.objects.filter_active(id=si).first()
        if ci:
            web = ci.title
    user_info['web'] = web
    return user_info


def get_permissions_tree(permissions, username):
    l = copy.deepcopy(BusinessPermission.PERMISSION_MAP)
    print username
    print permissions
    if username == u"admin":
        return l
    for item in l[::-1]:
        if item['depth'] == 1:
            for i in item['pids'][::-1]:
                if i['pid'] not in permissions:
                    item['pids'].remove(i)
        if item['depth'] == 2:
            for j in item['pids'][::-1]:
                for k in j['pids'][::-1]:
                    if k['pid'] not in permissions:
                        j['pids'].remove(k)
                if not j['pids']:
                    item['pids'].remove(j)
        if not item['pids']:
            l.remove(item)
    return l


def phone_check(phone):
    if phone:
        if len(phone) != 11 or not phone.isdigit():
            return False
    return True


# @receiver(post_save)
def company_registry(sender, **kwargs):
    if not TO_GOV:
        return
    # li = [CompanyInfo, Person, ElevatorInfo, Contract]
    obj = kwargs['instance']
    # print "kwargs: %s " % kwargs
    if obj.__class__ == CompanyInfo and obj.company_type != 100:
        return
    test_for_celery.delay(obj.__class__.__name__, obj.id)
    print '捕捉到信号，业已启动备案'


def elevator_delete(sender, **kwargs):
    if not TO_GOV:
        return
    obj = kwargs['instance']
    test_for_celery.delay(obj.__class__.__name__ + 'Delete', obj.id)
    print '捕捉到删除电梯信号'


def get_elevators(register_code, internal_no, property_company_name, maintain_company_name, page=1, page_size_count=8,):
    try:
        connect = mysql_singleton.MySQLSingle().get_conn()
        cursor = connect.cursor()
        sql_total = "select count(1) as total from lift_info"
        cursor.execute(sql_total)
        total = cursor.fetchone()['total']
        sql = "select li.EQULOGCODE as register_code, li.EQUORGNO as internal_no, li.USEORGNAME as property_company_name, lei.MAIORGNAME as maintain_company_name from lift_info li left join lift_extinfo lei on li.EQUDATASYSID = lei.EQUDATASYSID WHERE 1 = 1"
        start = (int(page) - 1) * int(page_size_count)
        if register_code:
            sql += " and li.EQULOGCODE like '%" + register_code + "%'"
        if internal_no:
            sql += " and li.EQUORGNO like '%" + internal_no + "%'"
        if property_company_name:
            sql += " and li.USEORGNAME like '%" + property_company_name + "%'"
        if maintain_company_name:
            sql += " and li.MAIORGNAME like '%" + maintain_company_name + "%'"

        sql = sql + " limit %s, %s" % (start, page_size_count)
        print sql
        cursor.execute(sql)
        data = cursor.fetchall()
        connect.close()
        cursor.close()
    except Exception as e:
        data = None
        total = 0
        print e
    return total, data


def query_elevators(register_codes):
    if not register_codes:
        return []
    try:
        connect = mysql_singleton.MySQLSingle().get_conn()
        cursor = connect.cursor()
        sql = "select li.EQULOGCODE as register_code, li.EQUORGNO as internal_no, li.USEORGNAME as property_company_name, lei.MAIORGNAME as maintain_company_name from lift_info li left join lift_extinfo lei on li.EQUDATASYSID = lei.EQUDATASYSID"
        if register_codes:
            sql += " where li.EQULOGCODE in ("
            for i in register_codes:
                sql += "'" + i + "',"
            sql = sql.rstrip(",")
            sql += ")"
        else:
            sql += " where 1 > 1"
        print sql
        cursor.execute(sql)
        data = cursor.fetchall()
        connect.close()
        cursor.close()
    except Exception as e:
        print e
        data = []
    return data


class PeopleRegisterView(AuthenticationExceptView, WdCreateAPIView):
    u"""用户注册接口"""

    POST_CHECK_REQUEST_PARAMETER = ('username', 'pwd')
    serializer_class = AuthUserSerializer
    model = AuthUser
    POST_DATA_ID_RESPONSE = True
    POST_DATA_RESPONSE = True

    def post_check_parameter(self, kwargs):
        if self.POST_CHECK_REQUEST_PARAMETER:
            for parameter in self.POST_CHECK_REQUEST_PARAMETER:
                setattr(self, parameter, kwargs.get(parameter, None))
                if getattr(self, parameter) is None:
                    return ErrorCode.INVALID_INPUT
        password = self.request.data.pop('pwd')
        password = make_password(password)
        self.request.data.update({'password': password})
        return ErrorCode.SUCCESS


class PeopleDetailView(WdRetrieveUpdateAPIView):

    POST_CHECK_REQUEST_PARAMETER = ('username', 'pwd', 'old_pwd')
    serializer_class = AuthUserSerializer
    model = AuthUser
    POST_DATA_ID_RESPONSE = True
    POST_DATA_RESPONSE = True

    def post_check_parameter(self, kwargs):
        code = super(PeopleDetailView, self).post_check_parameter(kwargs)
        if code != ErrorCode.SUCCESS:
            return code
        pwd = self.request.data.pop('pwd', None)
        old_pwd = self.request.data.pop('old_pwd', None)
        username = self.request.data.get('username', None)
        if pwd and old_pwd and username:
            user = authenticate(username=username, password=old_pwd)
            if not user:
                return ErrorCode.USER_PWD_ERROR
            else:
                password = make_password(pwd)
                self.request.data.update({'password': password})
        return code


class LoginView(AuthenticationExceptView, WdCreateAPIView):
    u"""用户登录接口
    """
    model = AuthUser
    serializer_class = AuthUserSerializer

    def post(self, request, *args, **kwargs):
        username = request.data.get('username', None)
        pwd = request.data.get("pwd", None)
        code_id = request.data.get("code_id", None)
        code = request.data.get("code", None)
        if not username or not pwd or not code_id or not code:
            return general_json_response(status.HTTP_200_OK, ErrorCode.INVALID_INPUT)
        r = redis.Redis(host=settings.redis_host, port=6379, db=3, password=settings.redis_password)
        if code != r.get(code_id):
            return general_json_response(status.HTTP_200_OK, ErrorCode.USER_PIC_CODE_INVALID)
        r.set(code_id, code, px=1)
        user = authenticate(username=username, password=pwd)
        if not user:
            r.set(code_id, code, px=1)
            return general_json_response(status.HTTP_200_OK, ErrorCode.USER_PWD_ERROR)
        if user.role in [10]:
            r.set(code_id, code, px=1)
            return general_json_response(status.HTTP_200_OK, ErrorCode.PERMISSION_FAIL)
        r.set(code_id, code, px=1)
        login(request, user)
        user_info = get_user_info(request, user, self.get_serializer_context())
        return general_json_response(status.HTTP_200_OK, ErrorCode.SUCCESS, user_info)


class LoginViewForLazyGirl(AuthenticationExceptView, WdCreateAPIView):
    u""" 用户登录接口 """
    model = AuthUser
    serializer_class = AuthUserSerializer

    def post(self, request, *args, **kwargs):
        ip = get_ip(request)
        ips = ["58.215.18.119", "2.20.121.14", "180.109.80.68"]
        print "ip: %s" % ip
        if ip in ips:
            user = AuthUser.objects.filter(username=u"guanliju").first()
            login(request, user)
            user_info = get_user_info(request, user, self.get_serializer_context())
            return general_json_response(status.HTTP_200_OK, ErrorCode.SUCCESS, user_info)
        return general_json_response(status.HTTP_200_OK, ErrorCode.FAILURE)


# class GetPicCodeView(AuthenticationExceptView, WdAPIView):
class GetPicCodeView(AuthenticationExceptView):

    renderer_classes = (TemplateHTMLRenderer,)

    def get(self, request, *args, **kwargs):
        codes = get_random_char_list(4)
        cache_code = "".join(codes)
        r = redis.Redis(host=settings.redis_host, port=6379, db=3, password=settings.redis_password)
        code_id = str(uuid.uuid4()).replace("-", "")
        r.set(code_id, cache_code, ex=600)
        value = piccode.create_piccode(codes)
        data = {
            "code": "data:image/png;base64," + value,
            "code_id": code_id,
            "platform": platform_name,
            "copyright": copyright,
            "record_number": record_number,
            "logo": logo,
            "logo_ico": logo_ico
        }
        return general_json_response(status.HTTP_200_OK, ErrorCode.SUCCESS, data)


class LogoutView(AuthenticationExceptView, WdCreateAPIView):
    u"""Web登出"""
    def post(self, request, *args, **kwargs):
        try:
            logout(request)
        except Exception, e:
            logger.error("web logout error, msg(%s)" % e)
        return general_json_response(status.HTTP_200_OK, ErrorCode.SUCCESS)


class PersonDetailView(WdRetrieveUpdateAPIView, WdDestroyAPIView):

    model = Person
    p_serializer_class = PersonSerializer
    g_serializer_class = PersonListSerializer
    POST_DATA_ID_RESPONSE = True
    POST_DATA_RESPONSE = True
    # POST_CHECK_REQUEST_PARAMETER = ('company', 'username', 'pwd', 'real_name', 'phone', 'card_id', 't1_card_no',
    #                                 't1_card_file', 't1_end_time', 't2_card_no', 't2_card_file', 't2_end_time',
    #                                 'contract_start_time', 'contract_end_time', 'contract_file', 'social_security')

    POST_CHECK_REQUEST_PARAMETER = ('company', 'username', 'real_name', 'phone', 'card_id', 'contract_start_time',
                                    'contract_end_time')

    def get_serializer_class(self, *args, **kwargs):
        if self.request.method.lower() == "get":
            return self.g_serializer_class
        elif self.request.method.lower() == "put":
            return self.p_serializer_class

    def post_check_parameter(self, kwargs):
        code = super(PersonDetailView, self).post_check_parameter(kwargs)
        if code != ErrorCode.SUCCESS:
            return code
        person_obj = self.get_object()
        old_card_id = person_obj.card_id
        new_card_id = self.request.data.get('card_id')
        if new_card_id != old_card_id:
            new_person_obj = Person.objects.filter_active(card_id=new_card_id).first()
            if new_person_obj:
                return ErrorCode.USER_ACCOUNT_EXISTS
        # company_id = self.request.data.get('company', None)
        contract_file = self.request.data.pop('contract_file', None)
        contract_file = json.dumps(contract_file)
        self.request.data['contract_file'] = contract_file
        # self.request.data.update({'service_id': company_id})

        user_obj = person_obj.auth_user
        user_name = self.request.data.pop('username')
        real_name = self.request.data.pop('real_name')
        phone = self.request.data.pop('phone')
        pwd = self.request.data.pop('pwd', None)
        if user_obj.username != user_name:
            user_obj.username = user_name
            user_obj.save()
        if user_obj.real_name != real_name:
            user_obj.real_name = real_name
            user_obj.save()
        if user_obj.phone != phone:
            user_obj.phone = phone
            user_obj.save()
        if pwd:
            pwd = make_password(pwd)
            user_obj.password = pwd
            user_obj.save()
        return code

    def perform_destroy(self, instance):
        if self.OBJECT_WITH_ACTIVE:
            person_obj = self.get_object()
            auth_obj = person_obj.auth_user
            auth_name = auth_obj.username
            auth_code = ''.join(random.sample(string.ascii_letters, 8))
            auth_name = auth_name + u'--' + auth_code
            auth_obj.username = auth_name
            auth_obj.is_active = False
            auth_obj.save()
            instance.is_active = False
            # 删除人员的同时，设置电梯人员绑定的状态，并提交市局更新
            elevator_person_qs = ElevatorPersonInfo.objects.filter(worker=person_obj.id)
            print elevator_person_qs.count()
            if elevator_person_qs.count():
                elevator_ids = []
                for obj in elevator_person_qs:
                    elevator_id = obj.elevator.id
                    if elevator_id not in elevator_ids:
                        elevator_ids.append(elevator_id)
                    obj.status = 20
                    obj.save()
                for reg_id in elevator_ids:
                    test_for_celery.delay('ElevatorInfo', reg_id)
            instance.save()
        else:
            instance.delete()


class PersonListCreateView(WdListCreateAPIView, WdDestroyAPIView):
    model = Person
    p_serializer_class = PersonSerializer
    g_serializer_class = PersonListSerializer
    POST_DATA_ID_RESPONSE = True
    POST_DATA_RESPONSE = True
    FILTER_FIELDS = ('status', 'registry_status')
    # POST_CHECK_REQUEST_PARAMETER = ('company', 'username', 'pwd', 'real_name', 'phone', 'card_id', 't1_card_no',
    #                                 't1_card_file', 't1_end_time', 't2_card_no', 't2_card_file', 't2_end_time',
    #                                 'contract_start_time', 'contract_end_time', 'contract_file', 'social_security')
    FOREIGN_SEARCH_FIELD_MAP = {'auth_user': [AuthUser, 'real_name'], 'company': [CompanyInfo, 'name']}
    POST_CHECK_REQUEST_PARAMETER = ('company', 'username', 'pwd', 'real_name', 'phone', 'card_id',
                                    'contract_start_time', 'contract_end_time')
    # DELETE_CHECK_REQUEST_PARAMETER = ('person_ids',)

    def get_serializer_class(self, *args, **kwargs):
        if self.request.method.lower() == "get":
            return self.g_serializer_class
        elif self.request.method.lower() == "post":
            return self.p_serializer_class

    def qs_search(self, qs):
        key_words = self.request.GET.get(self.SEARCH_KEY, None)
        if key_words is None or not key_words:
            return qs
        search_sql = self.process_foreign_search()
        if len(search_sql) == 0:
            return qs
        else:
            query = reduce(operator.or_, search_sql)
            qs = qs.filter(query)
        return qs

    def delete(self, request, *args, **kwargs):
        person_ids = self.request.data.get('person_ids', [])
        for person_id in person_ids:
            elevator_person_qs = ElevatorPersonInfo.objects.filter(worker=person_id)
            print elevator_person_qs.count()
            if elevator_person_qs.count():
                elevator_ids = []
                for obj in elevator_person_qs:
                    elevator_id = obj.elevator.id
                    if elevator_id not in elevator_ids:
                        elevator_ids.append(elevator_id)
                    obj.status = 20
                    obj.save()
                for reg_id in elevator_ids:
                    test_for_celery.delay('ElevatorInfo', reg_id)
        Person.objects.filter_active(id__in=person_ids).update(is_active=False)
        for person_id in person_ids:
            auth_user_obj = Person.objects.get(id=person_id).auth_user
            auth_name = auth_user_obj.username
            auth_code = ''.join(random.sample(string.ascii_letters, 8))
            auth_name = auth_name + u'--' + auth_code
            auth_user_obj.username = auth_name
            auth_user_obj.is_active = False
            auth_user_obj.save()
        return general_json_response(status.HTTP_200_OK, ErrorCode.SUCCESS)

    # def qs_business_role(self, qs):
    #     user = self.request.user
    #     if user.role == 0:
    #         return qs
    #     company = user.company_info
    #     qs = qs.filter(company=company)
    #     return qs

    def post_check_parameter(self, kwargs):
        code = super(PersonListCreateView, self).post_check_parameter(kwargs)
        if code != ErrorCode.SUCCESS:
            return code
        card_id = self.request.data.get('card_id')
        person_obj = Person.objects.filter_active(card_id=card_id).first()
        if person_obj:
            return ErrorCode.USER_ACCOUNT_EXISTS
        company_id = self.request.data.get('company', None)
        password = self.request.data.pop('pwd')
        password = make_password(password)
        username = self.request.data.pop('username', None)
        real_name = self.request.data.pop('real_name', None)
        phone = self.request.data.pop('phone', None)
        contract_file = self.request.data.pop('contract_file', None)
        contract_file = json.dumps(contract_file)
        self.request.data['contract_file'] = contract_file
        try:
            auth_user = AuthUser.objects.create(username=username, password=password,
                                                real_name=real_name, phone=phone)
        except IntegrityError:
            logger.info(u"创建维保人员时账户重复")
            return ErrorCode.USER_ACCOUNT_EXISTS
        except Exception as e:
            logger.info(e)
            return ErrorCode.INVALID_INPUT
        self.request.data.update({'auth_user': auth_user.id})
        # self.request.data.update({'service_id': company_id})
        return code


class PersonBindListView(WdListCreateAPIView):
    model = Person
    p_serializer_class = None
    g_serializer_class = PersonBindListSerializer

    # def qs_business_role(self, qs):
    #     user = self.request.user
    #     if user.role == 20:
    #         com_obj = user.company_person.company
    #         qs = qs.filter(service_id=com_obj.id, registry_status=20)
    #     return qs

    def qs_filter(self, qs):
        qs = super(PersonBindListView, self).qs_filter(qs)
        qs = qs.filter(registry_status=20)
        return qs


class CompanyListCreateView(WdListCreateAPIView, WdDestroyAPIView):
    u"""单位创建 获取"""
    model = CompanyInfo
    p_serializer_class = CompanySerializer
    g_serializer_class = CompanyListSerializer
    POST_CHECK_REQUEST_PARAMETER = ('name', )
    GET_CHECK_REQUEST_PARAMETER = ('company_type', )
    SEARCH_FIELDS = ('name', )
    FILTER_FIELDS = ('company_type', 'registry_status')
    POST_DATA_RESPONSE = True
    # DELETE_CHECK_REQUEST_PARAMETER = ('company_ids',)
    FOREIGN_SEARCH_FIELD_MAP = {'company_person__auth_user': [AuthUser, 'username']}

    def qs_filter(self, qs):
        qs = super(CompanyListCreateView, self).qs_filter(qs)
        user = self.request.user
        if user.role == 30:
            com = CompanyPerson.objects.filter_active(auth_user=user).first().company
            qs = qs.filter(id=com.id)
        elif user.role == 40:
            qs = qs.filter(service_id=user.service_id)
        elif user.role == 0:
            # qs = qs.filter(id=F("service_id"))
            pass
        return qs

    def get_serializer_class(self, *args, **kwargs):
        if self.request.method.lower() == "get":
            return self.g_serializer_class
        elif self.request.method.lower() == "post":
            return self.p_serializer_class

    # def qs_search(self, qs):
    #     key_words = self.request.GET.get(self.SEARCH_KEY, None)
    #     if key_words is None or not key_words:
    #         return qs
    #     search_sql = self.process_foreign_search()
    #     if len(search_sql) == 0:
    #         return qs
    #     else:
    #         query = reduce(operator.or_, search_sql)
    #         qs = qs.filter(query)
    #     return qs

    def delete(self, request, *args, **kwargs):
        company_ids = self.request.data.get('company_ids', [])
        CompanyInfo.objects.filter_active(id__in=company_ids, company_type=300).update(is_active=False)
        for company_id in company_ids:
            company_obj = CompanyInfo.objects.get(id=company_id)
            auth_user_qs = company_obj.company_person.all()
            for auth_user_obj in auth_user_qs:
                auth_name = auth_user_obj.auth_user.username
                auth_code = ''.join(random.sample(string.ascii_letters, 8))
                auth_name = auth_name + u'--' + auth_code
                auth_user_obj.username = auth_name
                auth_user_obj.is_active = False
                auth_user_obj.save()
        return general_json_response(status.HTTP_200_OK, ErrorCode.SUCCESS)

    # 单位账户的创建
    def post_check_parameter(self, kwargs):
        code = super(CompanyListCreateView, self).post_check_parameter(kwargs)
        if code != ErrorCode.SUCCESS:
            return code

        company_type = self.request.data.get('company_type')
        user = self.request.user
        # if company_type != 100 and user.role == 0:
        #     return ErrorCode.PERMISSION_FAIL
        self.request.data['create_by'] = user.id

        company_name = self.request.data.get('name')
        if int(company_type) == 100:
            com_obj = CompanyInfo.objects.filter_active(name=company_name, company_type=100).first()
            if com_obj:
                return ErrorCode.USER_ACCOUNT_EXISTS
        elif int(company_type) == 300:
            # service_id = user.company_person.company.id
            com_obj = CompanyInfo.objects.filter_active(name=company_name, company_type=300, service_id=self.request.user.service_id).first()
            if com_obj:
                return ErrorCode.ENTERPRISE_CNNAME_EXISTS
        else:
            pass
        # password = self.request.data.pop('pwd')
        # password = make_password(password)
        # username = self.request.data.pop('username', None)

        # if company_type == 100:
        #     role = 20
        # elif company_type == 300:
        #     role = 30
        # try:
        #     auth_user_obj = AuthUser.objects.create(username=username, password=password, role=role)
        # except Exception as e:
        #     logger.info(e)
        #     return ErrorCode.USER_ACCOUNT_EXISTS
        # self.request.data.update({'auth_user': auth_user_obj.id})
        return code

    # 维保网点的创建
    def perform_create(self, serializer):
        super(CompanyListCreateView, self).perform_create(serializer)
        company_id = serializer.data['id']
        company_obj = self.model.objects.get(id=company_id)
        # com = CompanyInfo.objects.filter(id=company_id).first()
        # com.service_id = company_id
        # com.save()
        # 用service_id来标定不同的维保公司可以创建相同的使用单位
        if serializer.data['company_type'] == 300:
            auth_user = self.request.user
            if auth_user.role == 0:
                maintain_company_id = company_id
            else:
                maintain_company_id = auth_user.company_person.company.id
            # maintain_company_id = CompanyInfo.objects.filter_active(auth_user=auth_id).first().id
            company_obj.service_id = maintain_company_id
            print "222222"
            company_obj.save()
        elif serializer.data['company_type'] == 400:
            company_obj.service_id = company_id
            company_obj.save()
        elif serializer.data['company_type'] == 100:
            office_address = self.request.data.get('office_address')
            province_code = self.request.data.get('province_code')
            city_code = self.request.data.get('city_code')
            county_code = self.request.data.get('county_code')
            street_code = self.request.data.get('street_code')
            emergency_phone = self.request.data.get('emergency_phone')
            office_main_person = self.request.data.get('office_main_person')
            office_main_person_phone = self.request.data.get('office_main_person_phone')
            company_obj.service_id = company_id
            print "333333"
            company_obj.save()

            try:
                company_website_obj = CompanyWebsiteInfo.objects.create(office_address=office_address,
                                                                        province_code=province_code,
                                                                        city_code=city_code,
                                                                        county_code=county_code,
                                                                        street_code=street_code,
                                                                        emergency_phone=emergency_phone,
                                                                        office_main_person=office_main_person,
                                                                        office_main_person_phone=office_main_person_phone
                                                                        )
            except Exception as e:
                logger.info(e)
                return general_json_response(status.HTTP_200_OK, ErrorCode.USER_ACCOUNT_EXISTS)
            company_website_obj.company = company_obj
            company_website_obj.save()


class CompanyAutoSubmitView(WdCreateAPIView):

    def post(self, request, *args, **kwargs):
        company_id = self.request.data.get('company_id', None)
        auto_submit = self.request.data.get('auto_submit', None)
        user = self.request.user
        if user.role != 20:
            return general_json_response(status.HTTP_200_OK, ErrorCode.PERMISSION_FAIL)
        if not user.company_person.is_admin:
            return general_json_response(status.HTTP_200_OK, ErrorCode.PERMISSION_FAIL)
        if not company_id:
            return general_json_response(status.HTTP_200_OK, ErrorCode.INVALID_INPUT)
        cas = CompanyAutoSubmit.objects.filter_active(company_id=company_id).first()
        if not cas:
            CompanyAutoSubmit.objects.create(company_id=company_id, auto_submit=bool(auto_submit), service_id=company_id)
            return general_json_response(status.HTTP_200_OK, ErrorCode.SUCCESS)
        if auto_submit:
            cas.auto_submit = True
        else:
            cas.auto_submit = False
        cas.save()
        return general_json_response(status.HTTP_200_OK, ErrorCode.SUCCESS)


class CompanyDetailView(WdRetrieveUpdateAPIView, WdDestroyAPIView):
    model = CompanyInfo
    p_serializer_class = CompanySerializer
    g_serializer_class = CompanyListSerializer
    POST_DATA_RESPONSE = True
    POST_CHECK_REQUEST_PARAMETER = ('name', )

    def get_serializer_class(self, *args, **kwargs):
        if self.request.method.lower() == "get":
            return self.g_serializer_class
        elif self.request.method.lower() == "put":
            return self.p_serializer_class

    # def post_check_parameter(self, kwargs):
    #     if self.POST_CHECK_REQUEST_PARAMETER:
    #         for parameter in self.POST_CHECK_REQUEST_PARAMETER:
    #             setattr(self, parameter, kwargs.get(parameter, None))
    #             if getattr(self, parameter) is None:
    #                 return ErrorCode.INVALID_INPUT
    #     pwd = self.request.data.get('pwd', None)
    #     old_pwd = self.request.data.get('old_pwd')
    #     username = self.request.data.get('user_name')
    #     if pwd and old_pwd and username:
    #         user = authenticate(username=username, password=old_pwd)
    #         if not user:
    #             return general_json_response(status.HTTP_200_OK, ErrorCode.USER_PWD_ERROR)
    #         else:
    #             password = self.request.data.pop('pwd')
    #             password = make_password(password)
    #             self.request.data.update({'password': password})
    #     return ErrorCode.SUCCESS

    # 修改密码和账户名
    def post_check_parameter(self, kwargs):
        user = self.request.user
        code = super(CompanyDetailView, self).post_check_parameter(kwargs)
        if code != ErrorCode.SUCCESS:
            return code
        # 修改账户和密码
        obj = self.get_object()
        # if self.request.data.has_key('username'):
        #     # TODO 能否更改账户名称 ？能否不输入老密码而进行直接修改
        #     global company_obj
        company_obj = self.get_object()
        #     user_obj = company_obj.auth_user
        #     user_name = self.request.data.pop('username')
        #     if user_obj.username != user_name:
        #         user_obj.username = user_name
        #         user_obj.save()
        #     pwd = self.request.data.pop('pwd', None)
        #     if pwd:
        #         pwd = make_password(pwd)
        #         user_obj.password = pwd
        #         user_obj.save()
        # 修改维保网点信息

        company_name = self.request.data.get('name')
        if company_name != obj.name:
            if int(obj.company_type) == 100:
                com_obj = CompanyInfo.objects.filter_active(name=company_name, company_type=100).exclude(id=self.get_id()).first()
                if com_obj:
                    return ErrorCode.USER_ACCOUNT_EXISTS
            elif int(obj.company_type) == 300:
                # service_id = user.company_person.company.id
                com_obj = CompanyInfo.objects.filter_active(name=company_name, company_type=300, service_id=user.service_id).exclude(id=self.get_id()).first()
                if com_obj:
                    return ErrorCode.ENTERPRISE_CNNAME_EXISTS
            else:
                pass

        if self.request.user.role == 20 and self.get_object().company_type == 100 and self.request.data.has_key('office_address'):
            office_address = self.request.data.get('office_address')
            province_code = self.request.data.get('province_code')
            city_code = self.request.data.get('city_code')
            county_code = self.request.data.get('county_code')
            street_code = self.request.data.get('street_code')
            emergency_phone = self.request.data.get('emergency_phone')
            office_main_person = self.request.data.get('office_main_person')
            office_main_person_phone = self.request.data.get('office_main_person_phone')
            website_obj = CompanyWebsiteInfo.objects.get(company=company_obj.id)
            if website_obj.office_address != office_address:
                website_obj.office_address = office_address
            if website_obj.province_code != province_code:
                website_obj.province_code = province_code
            if website_obj.city_code != city_code:
                website_obj.city_code = city_code
            if website_obj.county_code != county_code:
                website_obj.county_code = county_code
            if website_obj.street_code != street_code:
                website_obj.street_code = street_code
            if website_obj.emergency_phone != emergency_phone:
                website_obj.emergency_phone = emergency_phone
            if website_obj.office_main_person != office_main_person:
                website_obj.office_main_person = office_main_person
            if website_obj.office_main_person_phone != office_main_person_phone:
                website_obj.office_main_person_phone = office_main_person_phone
            website_obj.save()
        return code

    def delete_check_parameter(self, kwargs):
        code = super(CompanyDetailView, self).delete_check_parameter(kwargs)
        if code != ErrorCode.SUCCESS:
            return code
        role = self.request.user.role
        obj = self.get_object()
        if (role == 20 and obj.company_type == 100) or (role == 30 and obj.company_type == 300) or (role == 40 and obj.company_type == 400):
            code = ErrorCode.CAN_NOT_DEL_SELF
        return code

    def perform_destroy(self, instance):
        if self.OBJECT_WITH_ACTIVE:
            company_id = self.get_object().id
            company_auth_qs = CompanyPerson.objects.filter_active(company=company_id)
            for company_person_obj in company_auth_qs:
                auth_obj = company_person_obj.auth_user
                auth_name = auth_obj.username
                auth_code = u''.join(random.sample(string.ascii_letters, 8))
                auth_name = auth_name + u'--' + auth_code
                auth_obj.username = auth_name
                auth_obj.is_active = False
                auth_obj.save()
                print auth_obj.is_active
            company_auth_qs.update(is_active=False)
            instance.is_active = False
            instance.save()
        else:
            instance.delete()


class CompanyPersonListCreteView(WdListCreateAPIView, WdDestroyAPIView):
    model = CompanyPerson
    p_serializer_class = CompanyPersonSerializer
    g_serializer_class = CompanyPersonListSerializer
    POST_CHECK_REQUEST_PARAMETER = ('username', 'pwd', 'person_type', 'company')
    GET_CHECK_REQUEST_PARAMETER = ('person_type', )
    POST_DATA_ID_RESPONSE = True
    POST_DATA_RESPONSE = True
    # SEARCH_FIELDS = ()
    QUERY_WITH_ACTIVE = True
    FOREIGN_SEARCH_FIELD_MAP = {'auth_user': [AuthUser, 'username'], 'company': [CompanyInfo, 'name']}

    def get_serializer_class(self, *args, **kwargs):
        if self.request.method.lower() == "get":
            return self.g_serializer_class
        elif self.request.method.lower() == "post":
            return self.p_serializer_class

    def get_queryset(self):
        qs = super(CompanyPersonListCreteView, self).get_queryset()
        person_type = self.request.GET.get('person_type', None)
        qs = qs.filter(person_type=person_type)
        return qs

    def delete(self, request, *args, **kwargs):
        c_p_s = self.request.data.get('usernames', [])
        c_p_s = self.model.objects.filter(id__in=c_p_s)
        for c in c_p_s:
            if c.is_admin:
                return general_json_response(status.HTTP_200_OK, ErrorCode.DELETE_NOT_ALLOWED)
        c_p_s.update(is_active=False)
        for c_p in c_p_s:
            auth_user = c_p.auth_user
            auth_user.username = self.gen_new_username(auth_user.username)
            auth_user.is_active = False
            auth_user.save()

        return general_json_response(status.HTTP_200_OK, ErrorCode.SUCCESS)

    def gen_new_username(self, username):
        s = unicode(''.join(random.sample(string.ascii_letters, 8)))
        return username + u'--' + s

    def post_check_parameter(self, kwargs):

        code = super(CompanyPersonListCreteView, self).post_check_parameter(kwargs)
        if code != ErrorCode.SUCCESS:
            return code
        if self.request.user.role == 0:
            c_p = CompanyPerson.objects.filter_active(company=self.request.data['company'], is_admin=True).first()
            if c_p:
                code = ErrorCode.ADMIN_EXITS
                return code
            self.request.data['is_admin'] = True
        pwd = self.request.data.pop('pwd', None)
        username = self.request.data.pop('username', None)
        if u' ' in username or len(username) < 5:
            code = ErrorCode.INVALID_INPUT
            return code
        password = make_password(pwd)
        person_type = self.request.data.get('person_type')
        if person_type == 10:
            role = 20
        elif person_type == 20:
            role = 30
        else:
            code = ErrorCode.INVALID_INPUT
            return code
        phone = self.request.data.get('phone', None)
        if phone:
            b = phone_check(phone)
            if not b:
                return ErrorCode.WRONG_PHONE
        real_name = self.request.data.get('real_name', None)
        try:
            auth_user_obj = AuthUser.objects.create(username=username, password=password, role=role,
                                                    real_name=real_name, phone=phone)
        except Exception as e:
            logger.info(e)
            code = ErrorCode.USER_ACCOUNT_EXISTS
            return code
        self.request.data['auth_user'] = auth_user_obj.id
        # self.request.data['company_id'] = self.request.user.service_id
        print self.request.data
        return code

    def qs_search(self, qs):
        key_words = self.request.GET.get(self.SEARCH_KEY, None)
        if key_words is None or not key_words:
            return qs
        search_sql = self.process_foreign_search()
        if len(search_sql) == 0:
            return qs
        else:
            query = reduce(operator.or_, search_sql)
            qs = qs.filter(query)
        return qs

    def perform_create(self, serializer):
        super(CompanyPersonListCreteView, self).perform_create(serializer)
        if self.request.user.role == 0:
            obj = CompanyPerson.objects.get(id=serializer.data['id'])
            obj.service_id = obj.company.id
            obj.save()


class CompanyPersonDetailView(WdRetrieveUpdateAPIView, WdDestroyAPIView):
    model = CompanyPerson
    p_serializer_class = CompanyPersonSerializer
    g_serializer_class = CompanyPersonListSerializer
    POST_DATA_ID_RESPONSE = True
    POST_DATA_RESPONSE = True

    def get_serializer_class(self, *args, **kwargs):
        if self.request.method.lower() == "get":
            return self.g_serializer_class
        elif self.request.method.lower() == "put":
            return self.p_serializer_class

    def delete_check_parameter(self, kwargs):
        code = super(CompanyPersonDetailView, self).delete_check_parameter(kwargs)
        if code != ErrorCode.SUCCESS:
            return code
        cp = self.get_object()
        user = self.request.user
        if user.role == 0 and not cp.is_admin:
            code = ErrorCode.DELETE_NOT_ALLOWED
            return code
        if user.role != 0 and cp.is_admin:
            code = ErrorCode.DELETE_NOT_ALLOWED
            return code
        return code

    def post_check_parameter(self, kwargs):
        code = super(CompanyPersonDetailView, self).post_check_parameter(kwargs)
        if code != ErrorCode.SUCCESS:
            return code
        cp = self.get_object()
        user = self.request.user
        if user.role == 0 and not cp.is_admin:
            code = ErrorCode.PUT_NOT_ALLOWED
            return code
        if user.role != 0 and cp.is_admin:
            code = ErrorCode.PUT_NOT_ALLOWED
            return code
        self.request.data.pop('company', None)
        pwd = self.request.data.pop('pwd', None)
        username = self.request.data.pop('username', None)
        old_username = self.request.data.pop('old_username', None)
        phone = self.request.data.get('phone', None)
        if phone:
            # r = r'^(13\d|14[5|7]|15\d|166|17[3|6|7]|18\d)\d{8}$'
            # phone_pattern = re.compile(r)
            # b = phone_pattern.match(phone)
            # if not b:
            b = phone_check(phone)
            if not b:
                return ErrorCode.WRONG_PHONE
        real_name = self.request.data.get('real_name', None)
        auth_user = AuthUser.objects.filter(username=old_username).first()
        if auth_user:
            if username:
                try:
                    auth_user.username = username
                    auth_user.save()
                except IntegrityError:
                    logger.info(u"创建维保人员时账户重复")
                    return ErrorCode.USER_ACCOUNT_EXISTS
                except Exception as e:
                    logger.info(e)
                    return ErrorCode.INVALID_INPUT
            if pwd:
                password = make_password(pwd)
                auth_user.password = password
            auth_user.real_name = real_name
            auth_user.phone = phone
            auth_user.save()
        return code

    def perform_destroy(self, instance):
        super(CompanyPersonDetailView, self).perform_destroy(instance)
        company_persons = instance.company_person.all()
        for i in company_persons:
            auth = i.auth_user
            auth.username += u"--" + unicode(''.join(random.sample(string.ascii_letters, 8)))
            auth.is_active = 0
            auth.save()


class CompanyListView(WdListAPIView):
    model = CompanyInfo
    serializer_class = CompanyListSerializerV2
    SEARCH_FIELDS = ("name",)
    FILTER_FIELDS = ('company_type', )


class RecordListView(WdListAPIView):
    model = Records
    serializer_class = RecordsListSerializer
    FILTER_FIELDS = ('ip', 'user_id', 'is_anonymous', 'method', 'day_time', 'path')
    SEARCH_FIELDS = ('user_agent', )
    QUERY_WITH_ACTIVE = False

    def qs_business_role(self, qs):
        user = self.request.user
        if user.role == 0:
            return qs
        else:
            # raise exceptions.PermissionDenied
            return qs.none()

    def qs_filter(self, qs):
        for filter_field in self.FILTER_FIELDS:
            field_value = self.request.GET.get(filter_field, None)
            if filter_field == u'day_time':
                if field_value:
                    year, month, day = field_value.split("-")
                    field_value = date(int(year), int(month), int(day))
            if field_value:
                qs = qs.filter(**{"%s" % filter_field: field_value})
        return qs


class RecordRetrieveView(WdRetrieveAPIView):
    model = Records
    serializer_class = RecordsListSerializer

    def get_object(self):
        obj = super(WdAPIView, self).get_object()
        user = self.request.user
        if user.role != 0:
            raise exceptions.PermissionDenied
        return obj


class AddressListView(WdListAPIView):
    # GET_CHECK_REQUEST_PARAMETER = ('address_code', )

    def get(self, request, *args, **kwargs):
        from ElevatorAdmin.settings import website
        # address_code = self.request.GET.get('address_code', None)
        # data = [item for item in website if item['address_code'] == address_code]
        # res = []
        # for item in data:
        #     res.extend(item['children'])
        return general_json_response(status.HTTP_200_OK, ErrorCode.SUCCESS, website)


class QueryAllPermissions(WdListAPIView):

    def get(self, request, *args, **kwargs):
        # 直接赋值给l的话，存储的PERMISSION_MAP 始终指向同一个内存，一个修改PERMISSION_MAP后，另一个人也会受影响
        # print "类属性: %s" % id(BusinessPermission.PERMISSION_MAP)
        # print "对象属性: %s " % id(BusinessPermission().PERMISSION_MAP)
        username = self.request.user.username
        permissions = get_permission(request.session['ep'])
        # for item in l[::-1]:
        #     if item['depth'] == 1:
        #         for i in item['pids'][::-1]:
        #             if i['pid'] not in permissions:
        #                 item['pids'].remove(i)
        #     if item['depth'] == 2:
        #         for j in item['pids'][::-1]:
        #             for k in j['pids'][::-1]:
        #                 if k['pid'] not in permissions:
        #                     j['pids'].remove(k)
        #             if not j['pids']:
        #                 item['pids'].remove(j)
        #     if not item['pids']:
        #         l.remove(item)
        l = get_permissions_tree(permissions, username)
        return general_json_response(status.HTTP_200_OK, ErrorCode.SUCCESS, l)


class ElevatorForRoleView(WdListAPIView):

    model = ElevatorInfo
    serializer_class = ElevatorSerializer
    SEARCH_FIELDS_FOREACH = ("supervised", "register_code", "internal_no", "maintain_company_name",
                             "property_company_name")

    def qs_filter(self, qs):
        qs = super(ElevatorForRoleView, self).qs_filter(qs)
        qs = qs.filter(~Q(register_code=''), ~Q(register_code=None))
        supervised = self.request.GET.get("supervised", None)
        if supervised == "1":
            qs = qs.filter(supervised=1)
        user = self.request.user
        if user.role == 0:
            pass
        elif user.role == 10:
            qs = qs.none()
        elif user.role in (20, 30, 40):
            if not user.company_person.is_admin:
                myes = user.elevators()
                organization = self.request.GET.get("organization", None)
                if not organization:
                    qs = qs.none()
                else:
                    es = OrganizationElevatorRelation.objects.filter_active(organization_id=organization, register_code__in=myes).values_list("register_code", flat=True).distinct()
                    qs = qs.filter(register_code__in=es)
        else:
            qs = qs.none()

        # if user.username == u"admin" or (user.role == 0 and user.permit_all) or (user.role != 0 and user.company_person.is_admin):
        #     pass
        # elif user.permission_type == 20:
        #     rg = AuthUserElevatorRelation.objects.filter_active(auth_user=user).values_list("register_code", flat=True).distinct()
        #     qs = qs.filter(register_code__in=rg)
        # elif not user.admin_role:
        #     qs = qs.none()
        # elif user.admin_role.management_type == 20:
        #     rg = ElevatorAdminRoRelation.objects.filter_active(admin_role=user.admin_role).values_list("register_code", flat=True).distinct()
        #     qs = qs.filter(register_code__in=rg)
        # else:
        #     oarr = OrganizationAdminRoRelation.objects.filter_active(admin_role=user.admin_role).first()
        #     if not oarr or not oarr.organization:
        #         qs = qs.none()
        #     else:
        #         rg = OrganizationElevatorRelation.objects.filter_active(organization=oarr.organization).values_list("register_code", flat=True).distinct()
        #         qs = qs.filter(register_code__in=rg)
        return qs

    def get(self, request, *args, **kwargs):
        lift = self.request.GET.get("lift", None)
        supervised = self.request.GET.get("supervised", None)
        register_code = self.request.GET.get("register_code", None)
        internal_no = self.request.GET.get("internal_no", None)
        property_company_name = self.request.GET.get("property_company_name", None)
        maintain_company_name = self.request.GET.get("maintain_company_name", None)
        page = self.request.GET.get("page", 1)
        page_size_count = self.request.GET.get("page_size_count", 8)
        if lift == "1" and not supervised:
            total, data = get_elevators(register_code, internal_no, property_company_name, maintain_company_name, page,
                                        page_size_count)
            res = {"count": total, "results": data}
            return general_json_response(status.HTTP_200_OK, ErrorCode.SUCCESS, res)
        elif lift == "1" and supervised == "1":
            qs = BasicSupervisedRelation.objects.filter_active()
            if register_code:
                qs = qs.filter(register_code__icontains=register_code)
            if internal_no:
                qs = qs.filter(internal_no__icontains=internal_no)
            if property_company_name:
                qs = qs.filter(property_company_name__icontains=property_company_name)
            if maintain_company_name:
                qs = qs.filter(maintain_company_name__icontains=maintain_company_name)
            total = qs.count()
            start = (int(page) - 1) * int(page_size_count)
            end = int(page) * int(page_size_count)
            qs = qs[start: end]
            data = qs.values("register_code", "internal_no", "maintain_company_name", "property_company_name")
            res = {"count": total, "results": data}
            return general_json_response(status.HTTP_200_OK, ErrorCode.SUCCESS, res)
        try:
            response = super(WdListAPIView, self).get(request, *args, **kwargs)
        except NotFound, e:  # paginate_queryset raise NotFound
            return general_json_response(status.HTTP_200_OK, ErrorCode.SUCCESS, [])
        response = general_json_response(status.HTTP_200_OK, ErrorCode.SUCCESS, response.data)
        return response


class CompanyForAuthUserView(WdListAPIView):

    model = CompanyInfo
    serializer_class = CompanyForAuthUserSerializer
    SEARCH_FIELDS = ("name", )
    FILTER_FIELDS = ("company_type", )

    def qs_filter(self, qs):
        qs = super(CompanyForAuthUserView, self).qs_filter(qs)
        role = self.request.user.role
        if role == 0:
            ids = CompanyPerson.objects.filter_active().values_list("company_id", flat=True).distinct()
            qs = qs.filter(company_type__in=(100, 300, 400)).exclude(id__in=ids)
        elif role == 20:
            ids = CompanyPerson.objects.filter_active(company__company_type=300).values_list("company_id", flat=True).distinct()
            qs = qs.filter(company_type__in=(100, 300)).exclude(id__in=ids)
        elif role == 30:
            cid = CompanyPerson.objects.filter_active(auth_user=self.request.user).first().company.id
            qs = qs.filter(id=cid)
        # # elif role == 30:
        # #     qs = qs.filter(company_type=300)
        # # elif role == 40:
        # #     qs = qs.filter(company_type=400)
        # # else:
        #     # role == 30
        #     qs = qs.none()
        return qs


class ElevatorForSupervisionView(WdAPIView):

    def post(self, request, *args, **kwargs):
        register_codes = self.request.data.get("register_codes", [])
        lift = self.request.data.get("lift", None)
        if lift == "0":
            ElevatorInfo.objects.filter_active(register_code__in=register_codes).update(supervised=1)
        else:
            l = query_elevators(register_codes)
            bulk_list = []
            old = BasicSupervisedRelation.objects.filter_active().values_list("register_code", flat=True).distinct()
            for i in l:
                if i['register_code'] in old:
                    continue
                bulk_list.append(BasicSupervisedRelation(register_code=i['register_code'], internal_no=i['internal_no'],
                                                         maintain_company_name=i['maintain_company_name'],
                                                         property_company_name=i['property_company_name']))
            if bulk_list:
                BasicSupervisedRelation.objects.bulk_create(bulk_list)
        return general_json_response(status.HTTP_200_OK, ErrorCode.SUCCESS)

    def delete(self, request, *args, **kwargs):
        register_codes = self.request.data.get("register_codes", [])
        lift = self.request.data.get("lift", None)
        if not lift:
            ElevatorInfo.objects.filter_active(register_code__in=register_codes).update(supervised=0)
        else:
            BasicSupervisedRelation.objects.filter_active(register_code__in=register_codes).update(is_active=0)
        return general_json_response(status.HTTP_200_OK, ErrorCode.SUCCESS)


class AdminRoleListCreateView(WdListCreateAPIView):

    model = AdminRole
    serializer_class = AdminRoleSerializer
    POST_CHECK_REQUEST_PARAMETER = ('role_name', 'role_desc', "management_type", "management")
    POST_DATA_ID_RESPONSE = True
    POST_DATA_RESPONSE = True
    SEARCH_FIELDS = ("role_name", )
    FILTER_FIELDS = ("role_type", )

    def qs_filter(self, qs):
        qs = super(AdminRoleListCreateView, self).qs_filter(qs)
        # if self.request.user.username != u"admin":
        #     qs = qs.filter(create_by=self.request.user)
        # else:
        #     qs = qs.filter(service_id=0)
        user = self.request.user
        if user.username == u"admin":
            qs = qs.filter(create_by=self.request.user)
        else:
            qs = qs.filter(Q(create_for_all=1) | Q(id=user.admin_role_id) | Q(create_by=user))
        return qs

    def qs_business_role(self, qs):
        return qs

    def post_check_parameter(self, kwargs):
        code = super(AdminRoleListCreateView, self).post_check_parameter(kwargs)
        user = self.request.user
        if code != ErrorCode.SUCCESS:
            return code
        create_for_all = self.request.data.get("create_for_all", 0)
        if create_for_all and user.username != u"admin":
            return ErrorCode.ROLE_FOR_COMMON
        role_name = self.request.data.get("role_name", None)
        role = self.request.user.role
        if role == 0:
            company = None
        else:
            company = self.request.user.company_person.company.id
        if AdminRole.objects.filter_active(role_name=role_name, company_id=company).exists():
            code = ErrorCode.USER_ROLE_NAME_EXISTS
        self.request.data.update({"company": company})
        management_type = self.request.data.get("management_type", None)
        if management_type == 10 and user.permission_type == 20:
            code = ErrorCode.ROLE_NOT_PERMIT
            return code
        oids = user.org_permit()
        management = self.request.data.get("management", None)
        role_type = self.request.data.get("role_type", None)
        print management
        print oids
        if role == role_type:
            if -1 in oids:
                oids.remove(-1)
        if not oids:
            code = ErrorCode.USER_ORGANIZATION_NOT_PERMIT
        elif "all" in oids:
            pass
        else:
            if management not in oids:
                code = ErrorCode.USER_ORGANIZATION_NOT_PERMIT
        return code

    def perform_create(self, serializer):
        super(AdminRoleListCreateView, self).perform_create(serializer)
        obj = self.create_obj
        obj.create_by = self.request.user
        obj.save()
        permission_ids = self.request.data.get("permissions", [])
        aid = serializer.data.get("id", None)
        admin_role = AdminRole.objects.filter_active(id=aid).first()
        obj_list = []
        for permission_id in permission_ids:
            obj_list.append(RoleBusinessPermission(admin_role=admin_role, permission=permission_id, service_id=admin_role.service_id))
        if obj_list:
            RoleBusinessPermission.objects.bulk_create(obj_list)
        user = self.request.user
        role_type = self.request.data.get("role_type", None)
        cid = self.request.data.get("management", None)
        if cid == -1:
            OrganizationAdminRoRelation.objects.create(admin_role=obj, is_top=True)
        elif user.role == 0 and role_type != 0:
            OrganizationAdminRoRelation.objects.create(admin_role=obj, company_id=cid)
        elif user.role == 20:
            if role_type == 30:
                OrganizationAdminRoRelation.objects.create(admin_role=obj, company_id=cid)
            else:
                OrganizationAdminRoRelation.objects.create(admin_role=obj, organization_id=cid)
        elif user.role == 30:
            OrganizationAdminRoRelation.objects.create(admin_role=obj, organization_id=cid)
        elif user.role == 40:
            OrganizationAdminRoRelation.objects.create(admin_role=obj, organization_id=cid)
        # organizations = self.request.data.get("organizations", [])
        # bulk_list = []
        # for organization in organizations:
        #     bulk_list.append(OrganizationAdminRoRelation(organization_id=int(organization), admin_role_id=aid))
        # if bulk_list:
        #     OrganizationAdminRoRelation.objects.bulk_create(bulk_list)

        register_codes = self.request.data.get("register_codes", [])
        lift = self.request.data.get("lift", None)
        bulk_list = []
        if lift == "1":
            data = query_elevators(register_codes)
            for dic in data:
                bulk_list.append(ElevatorAdminRoRelation(admin_role_id=aid, register_code=dic['register_code'],
                                                         is_business=False, internal_no=dic['internal_no'],
                                                         maintain_company_name=dic['maintain_company_name'],
                                                         property_company_name=dic['property_company_name']))
        else:
            es = ElevatorInfo.objects.filter_active(register_code__in=register_codes)
            for e in es:
                bulk_list.append(ElevatorAdminRoRelation(admin_role_id=aid, register_code=e.register_code,
                                                         is_business=True, internal_no=e.internal_no,
                                                         maintain_company_name=e.maintain_company_name,
                                                         property_company_name=e.property_company_name,))
        if bulk_list:
            ElevatorAdminRoRelation.objects.bulk_create(bulk_list)


class AdminRoleDetailView(WdRetrieveUpdateAPIView, WdDestroyAPIView):

    model = AdminRole
    serializer_class = AdminRoleSerializer

    def check_user(self, user):
        obj = self.get_object()
        if obj.create_by == user:
            return True
        return False

    def delete_check_parameter(self, kwargs):
        code = super(AdminRoleDetailView, self).delete_check_parameter(kwargs)
        if code != ErrorCode.SUCCESS:
            return code
        obj = self.get_object()
        if obj.create_for_all and self.request.user.username != u"admin":
            return ErrorCode.ROLE_FOR_COMMON
        if not self.check_user(self.request.user):
            return ErrorCode.ROLE_FOR_SELF
        return code

    def delete(self, request, *args, **kwargs):
        obj = self.get_object()
        usernames = AuthUser.objects.filter(is_active=True, admin_role=obj).values_list("username", flat=True)
        if usernames:
            usernames = ",".join(usernames) + u" 正在使用这个角色,无法删除"
            return general_json_response(status.HTTP_200_OK, ErrorCode.FAILURE, usernames)
        self.OWN_PERMISSION_CHECK = self.DEL_OWN_PERMISSION_CHECK
        super(AdminRoleDetailView, self).delete(request, *args, **kwargs)
        return general_json_response(status.HTTP_200_OK, ErrorCode.SUCCESS)

    def perform_destroy(self, instance):
        super(AdminRoleDetailView, self).perform_destroy(instance)
        RoleBusinessPermission.objects.filter_active(admin_role=instance).update(is_active=False)
        OrganizationAdminRoRelation.objects.filter_active(admin_role_id=self.get_id()).update(is_active=False)
        ElevatorAdminRoRelation.objects.filter_active(admin_role_id=self.get_id()).update(is_active=False)

    def post_check_parameter(self, kwargs):
        code = super(AdminRoleDetailView, self).post_check_parameter(kwargs)
        if code != ErrorCode.SUCCESS:
            return code

        obj = self.get_object()
        if obj.create_for_all and self.request.user.username != u"admin":
            return ErrorCode.ROLE_FOR_COMMON
        if not self.check_user(self.request.user):
            return ErrorCode.ROLE_FOR_SELF
        role_name = self.request.data.get("role_name", None)
        role = self.request.user.role
        if role == 0:
            company = None
        else:
            company = self.request.user.company_person.company.id
        if AdminRole.objects.filter_active(role_name=role_name, company_id=company).exclude(id=self.get_id()).exists():
            code = ErrorCode.USER_ROLE_NAME_EXISTS
        self.request.data.update({"company": company})
        oids = self.request.user.org_permit()
        if not oids:
            code = ErrorCode.USER_ORGANIZATION_NOT_PERMIT
        elif "all" in oids:
            pass
        else:
            management = self.request.data.get("management", None)
            if management not in oids:
                code = ErrorCode.USER_ORGANIZATION_NOT_PERMIT
        return code

    def put(self, request, *args, **kwargs):
        obj = self.get_object()
        permission_ids = self.request.data.get("permissions", [])
        qs = RoleBusinessPermission.objects.filter_active(admin_role=obj)
        if qs:
            qs.update(is_active=False)
        obj_list = []
        for permission_id in permission_ids:
            obj_list.append(RoleBusinessPermission(admin_role=obj, permission=permission_id, service_id=obj.service_id))
        if obj_list:
            RoleBusinessPermission.objects.bulk_create(obj_list)

        user = self.request.user
        role_type = self.request.data.get("role_type", None)
        cid = self.request.data.get("management", None)
        aid = self.get_id()
        OrganizationAdminRoRelation.objects.filter_active(admin_role_id=aid).update(is_active=False)
        if cid == -1:
            OrganizationAdminRoRelation.objects.create(admin_role=obj, is_top=True)
        elif user.role == 0 and role_type != 0:
            OrganizationAdminRoRelation.objects.create(admin_role=obj, company_id=cid)
        elif user.role == 20:
            if role_type == 30:
                OrganizationAdminRoRelation.objects.create(admin_role=obj, company_id=cid)
            else:
                OrganizationAdminRoRelation.objects.create(admin_role=obj, organization_id=cid)
        elif user.role == 30:
            OrganizationAdminRoRelation.objects.create(admin_role=obj, organization_id=cid)
        elif user.role == 40:
            OrganizationAdminRoRelation.objects.create(admin_role=obj, organization_id=cid)
        # user = self.request.user
        # role = self.request.data.get("role_type", None)
        # if user.role == 0:
        #     self.request.data.pop("organizations", None)
        # elif user.role == 20:
        #     if role == 30:
        #         self.request.data.pop("organizations", None)

        # bulk_list = []
        # organizations = self.request.data.get("organizations", [])
        # for organization in organizations:
        #     bulk_list.append(OrganizationAdminRoRelation(organization_id=int(organization), admin_role_id=aid))
        # if bulk_list:
        #     OrganizationAdminRoRelation.objects.bulk_create(bulk_list)
        register_codes = self.request.data.get("register_codes", [])
        ElevatorAdminRoRelation.objects.filter_active(admin_role_id=aid).update(is_active=False)
        lift = self.request.data.get("lift", None)
        bulk_list = []
        if lift == "1":
            data = query_elevators(register_codes)
            for dic in data:
                bulk_list.append(ElevatorAdminRoRelation(admin_role_id=aid, register_code=dic['register_code'],
                                                         is_business=False, internal_no=dic['internal_no'],
                                                         maintain_company_name=dic['maintain_company_name'],
                                                         property_company_name=dic['property_company_name']))
        else:
            es = ElevatorInfo.objects.filter_active(register_code__in=register_codes)
            for e in es:
                bulk_list.append(ElevatorAdminRoRelation(admin_role_id=aid, register_code=e.register_code,
                                                         is_business=True, internal_no=e.internal_no,
                                                         maintain_company_name=e.maintain_company_name,
                                                         property_company_name=e.property_company_name, ))
        if bulk_list:
            ElevatorAdminRoRelation.objects.bulk_create(bulk_list)

        # register_codes = self.request.data.get("register_codes", [])
        # bulk_list = []
        # ElevatorAdminRoRelation.objects.filter_active(admin_role_id=aid).update(is_active=False)
        # for register_code in register_codes:
        #     bulk_list.append(ElevatorAdminRoRelation(admin_role_id=aid, register_code=register_code))
        # if bulk_list:
        #     ElevatorAdminRoRelation.objects.bulk_create(bulk_list)

        # if management_type == 10:
        #     ElevatorAdminRoRelation.objects.filter_active(admin_role_id=self.get_id()).update(is_active=False)
        #     organizations = self.request.data.get("organizations", [])
        #     oarr = OrganizationAdminRoRelation.objects.filter_active(admin_role_id=self.get_id())
        #     old_orgs = oarr.values_list("organization_id", flat=True).distinct()
        #     if sorted(organizations) != sorted(old_orgs):
        #         oarr.update(is_active=False)
        #         bulk_list = []
        #         for organization in organizations:
        #             bulk_list.append(OrganizationAdminRoRelation(organization_id=int(organization), admin_role_id=self.get_id()))
        #         if bulk_list:
        #             OrganizationAdminRoRelation.objects.bulk_create(bulk_list)
        # else:
        #     OrganizationAdminRoRelation.objects.filter_active(admin_role_id=self.get_id()).update(is_active=False)
        #     register_codes = self.request.data.get("register_codes", [])
        #     earr = ElevatorAdminRoRelation.objects.filter_active(admin_role_id=self.get_id())
        #     old_codes = earr.values_list("register_code", flat=True).distinct()
        #     if sorted(register_codes) != sorted(old_codes):
        #         earr.update(is_active=False)
        #         bulk_list = []
        #         for register_code in register_codes:
        #             bulk_list.append(ElevatorAdminRoRelation(admin_role_id=self.get_id(), register_code=register_code))
        #         if bulk_list:
        #             ElevatorAdminRoRelation.objects.bulk_create(bulk_list)

        if self.p_serializer_class is not None:
            self.serializer_class = self.p_serializer_class
        if self.partial:
            rsp = self.partial_update(request, *args, **kwargs)
        else:
            rsp = self.update(request, *args, **kwargs)
        # if self.UPDATE_TAG:
        #     self.perform_tag()
        if self.POST_DATA_RESPONSE:
            return general_json_response(status.HTTP_200_OK, ErrorCode.SUCCESS, rsp.data)
        else:
            return general_json_response(status.HTTP_200_OK, ErrorCode.SUCCESS)


class AuthUserParamView(WdAPIView):

    def get(self, request, *args, **kwargs):
        role = [{"name": u"平台管理员", "role": 0},
                {"name": u"维保人员", "role": 10},
                {"name": u"维保单位", "role": 20},
                {"name": u"使用单位", "role": 30},
                {"name": u"监管单位", "role": 40}]
        service_id = self.request.user.service_id
        if self.request.user.role != 0:
            coms = CompanyInfo.objects.filter_active(service_id=service_id).values("id", "name")
        else:
            coms = CompanyInfo.objects.filter_active().values("id", "name")
        data = {"role": role, "company": coms}
        return general_json_response(status.HTTP_200_OK, ErrorCode.SUCCESS, data)


class AuthUserListCreateView(WdListCreateAPIView):

    model = AuthUser
    serializer_class = AuthUserSerializer
    g_serializer_class = AuthUserListSerializer
    POST_CHECK_REQUEST_PARAMETER = ('username', 'pwd', 'real_name', 'gender', 'role', 'phone', 'admin_role')
    POST_DATA_ID_RESPONSE = True
    POST_DATA_RESPONSE = True
    SEARCH_FIELDS = ("username", "real_name")

    def qs_filter(self, qs):
        qs = super(AuthUserListCreateView, self).qs_filter(qs)
        qs = qs.exclude(username=u'admin')
        qs = qs.filter(is_active=1)
        role = self.request.user.role
        if role == 0:
            pass
            # aus = AuthUser.objects.filter(is_active=1, service_id=0, role=0).values_list("id", flat=True).distinct()
            # cpids = CompanyPerson.objects.filter_active(company__company_type__in=(100, 300, 400), is_admin=True).values_list("auth_user_id", flat=True).distinct()
            # qs = qs.filter(Q(id__in=cpids) | Q(id__in=aus))
        elif role == 30:
            com = CompanyPerson.objects.filter_active(auth_user=self.request.user).first().company
            ids = CompanyPerson.objects.filter_active(company=com).values_list("auth_user_id", flat=True).distinct()
            qs = qs.filter(id__in=ids)
        elif role == 40:
            qs = qs.filter(service_id=self.request.user.service_id)

        ro = self.request.GET.get("role", None)
        company = self.request.GET.get("company", None)
        if ro:
            ro = int(ro)
            qs = qs.filter(role=ro)
        if company:
            c = CompanyInfo.objects.filter_active(id=int(company)).first()
            if not c:
                qs = qs.none()
            # elif c.company_type in (100, 400):
            #     qs = qs.filter(service_id=c.id)
            elif c.company_type in (100, 300, 400):
                ids = CompanyPerson.objects.filter_active(company=c).values_list("auth_user_id", flat=True).distinct()
                qs = qs.filter(id__in=ids)
            else:
                qs = qs.none()
        return qs

    def post_check_parameter(self, kwargs):
        code = super(AuthUserListCreateView, self).post_check_parameter(kwargs)
        if code != ErrorCode.SUCCESS:
            return code
        a = AuthUser.objects.filter(username=self.request.data.get("username"))
        if a:
            return ErrorCode.USER_ACCOUNT_EXISTS
        password = self.request.data.pop('pwd')
        password = make_password(password)
        self.request.data.update({'password': password})
        phone = self.request.data.get('phone', None)
        organization = self.request.data.get("organization", None)
        if phone:
            b = phone_check(phone)
            if not b:
                return ErrorCode.WRONG_PHONE
        email = self.request.data.get('email', None)
        if email:
            r = r'^[a-zA-Z0-9_-]+@[a-zA-Z0-9]+(\.[a-zA-Z0-9]+)$'
            email_pattern = re.compile(r)
            b = email_pattern.match(email)
            if not b:
                return ErrorCode.USER_EMAIL_USED_ERROR

        user = self.request.user
        role = self.request.data.get("role", None)
        if user.role == 0:
            self.request.data.pop("organization", None)
        elif user.role == 20:
            if role == 30:
                self.request.data.pop("organization", None)
        # if organization:
        #     if user.username == u"admin" or (user.role == 0 and user.permit_all):
        #         if organization == -1:
        #             self.request.data.update({"organization": None, "permit_all": True})
        #     elif user.role in (20, 30) and user.company_person.is_admin:
        #         if organization == -1:
        #             return ErrorCode.USER_ORGANIZATION_NOT_PERMIT
        #     elif not user.organization:
        #         return ErrorCode.USER_ORGANIZATION_NOT_PERMIT
        #     elif organization and organization not in user.organization.children():
        #         return ErrorCode.USER_ORGANIZATION_NOT_PERMIT

        company = self.request.data.get("company", None)
        if company:
            # self.request.data.update({"service_id": company})
            if self.request.user.role == 0:
                c_p = CompanyPerson.objects.filter_active(company_id=company, is_admin=True).first()
                if c_p:
                    code = ErrorCode.ADMIN_EXITS
                    return code
            if self.request.user.role == 20:
                c = CompanyInfo.objects.get(id=company)
                if c.company_type == 300:
                    c_p = CompanyPerson.objects.filter_active(company_id=company, is_admin=True).first()
                    if c_p:
                        code = ErrorCode.ADMIN_EXITS
                        return code
        return ErrorCode.SUCCESS

    def perform_create(self, serializer):
        super(AuthUserListCreateView, self).perform_create(serializer)
        obj = self.create_obj
        aid = obj.id
        # obj.service_id = serializer.data.get("id")
        add_all = self.request.data.get("add_all", None)
        if add_all == 1:
            register_codes = ElevatorInfo.objects.filter_active().values_list("register_code", flat=True).distinct()
        else:
            register_codes = self.request.data.get("register_codes", [])

        # AuthUserElevatorRelation.objects.filter_active(admin_role_id=aid).update(is_active=False)
        lift = self.request.data.get("lift", None)
        bulk_list = []
        if lift == "1":
            data = query_elevators(register_codes)
            for dic in data:
                bulk_list.append(AuthUserElevatorRelation(auth_user_id=aid, register_code=dic['register_code'],
                                                          is_business=False, internal_no=dic['internal_no'],
                                                          maintain_company_name=dic['maintain_company_name'],
                                                          property_company_name=dic['property_company_name']))
        else:
            es = ElevatorInfo.objects.filter_active(register_code__in=register_codes)
            for e in es:
                bulk_list.append(AuthUserElevatorRelation(auth_user_id=aid, register_code=e.register_code,
                                                          is_business=True, internal_no=e.internal_no,
                                                          maintain_company_name=e.maintain_company_name,
                                                          property_company_name=e.property_company_name, ))
        if bulk_list:
            AuthUserElevatorRelation.objects.bulk_create(bulk_list)

        # aid = serializer.data.get("id")
        # elevators = ElevatorInfo.objects.filter_active(register_code__in=register_codes)
        # for e in elevators:
        #     bulk_list.append(AuthUserElevatorRelation(auth_user_id=aid, register_code=e.register_code,
        #                                               internal_no=e.internal_no,
        #                                               maintain_company_name=e.maintain_company_name,
        #                                               property_company_name=e.property_company_name)
        #                      )
        # if bulk_list:
        #     AuthUserElevatorRelation.objects.bulk_create(bulk_list)

        company = self.request.data.get("company", None)
        if company:
            c = CompanyInfo.objects.filter_active(id=company).first()
            if c:
                service_id = c.service_id
                if self.request.user.role == 0 and c.company_type == 100:
                    CompanyPerson.objects.create(company_id=company, is_admin=True, auth_user_id=aid, service_id=service_id)
                elif self.request.user.role == 0 and c.company_type == 300:
                    CompanyPerson.objects.create(company_id=company, is_admin=True, auth_user_id=aid, service_id=service_id)
                elif self.request.user.role == 0 and c.company_type == 400:
                    CompanyPerson.objects.create(company_id=company, is_admin=True, auth_user_id=aid, service_id=service_id)
                elif self.request.user.role == 20:
                    if c.company_type == 300:
                        CompanyPerson.objects.create(company_id=company, is_admin=True, auth_user_id=aid, service_id=service_id)
                    elif c.company_type == 100:
                        CompanyPerson.objects.create(company_id=company, auth_user_id=aid, service_id=service_id)
                elif self.request.user.role in (30, 40):
                    CompanyPerson.objects.create(company_id=company, auth_user_id=aid, service_id=service_id)
                if self.request.user.role == 0:
                    obj.service_id = service_id
                    obj.save()

        role = self.request.data.get("role", None)
        if role == 10:
            company = self.request.user.company_person.company
            auth_user_id = aid
            card_id = self.request.data.get("card_id", None)
            t1_card_no = self.request.data.get("t1_card_no", None)
            t1_card_file = self.request.data.get("t1_card_file", None)
            t1_end_time = self.request.data.get("t1_end_time", None)
            t2_card_no = self.request.data.get("t2_card_no", None)
            t2_card_file = self.request.data.get("t2_card_file", None)
            t2_end_time = self.request.data.get("t2_end_time", None)
            contract_start_time = self.request.data.get("contract_start_time", None)
            contract_end_time = self.request.data.get("contract_end_time", None)
            status = self.request.data.get("status", None)
            contract_file = self.request.data.get("contract_file", None)
            if contract_file:
                contract_file = json.dumps(contract_file)
            social_security = self.request.data.get("social_security", None)
            home_addr = self.request.data.get("home_addr", None)
            dic = {"auth_user_id": auth_user_id, "card_id": card_id, "t1_card_no": t1_card_no, "status": status,
                   "t1_card_file": t1_card_file, "t1_end_time": t1_end_time, "t2_card_no": t2_card_no,
                   "t2_card_file": t2_card_file, "t2_end_time": t2_end_time, "contract_start_time": contract_start_time,
                   "contract_end_time": contract_end_time, "company_id": company.id, "contract_file": contract_file,
                   "social_security": social_security, "service_id": company.id, "home_addr": home_addr}
            Person.objects.create(**dic)

    def post(self, request, *args, **kwargs):
        rsp = super(WdCreateAPIView, self).post(request, *args, **kwargs)
        company = self.request.data.get("company", None)
        data = rsp.data
        if company:
            c = CompanyInfo.objects.filter_active(id=company).first()
            data['company_id'] = c.id
            data['company_name'] = c.name
        role = self.request.data.get("role", None)

        if role == 10:
            card_id = self.request.data.get("card_id", None)
            t1_card_no = self.request.data.get("t1_card_no", None)
            t1_card_file = self.request.data.get("t1_card_file", None)
            t1_end_time = self.request.data.get("t1_end_time", None)
            t2_card_no = self.request.data.get("t2_card_no", None)
            t2_card_file = self.request.data.get("t2_card_file", None)
            t2_end_time = self.request.data.get("t2_end_time", None)
            contract_start_time = self.request.data.get("contract_start_time", None)
            contract_end_time = self.request.data.get("contract_end_time", None)
            s = self.request.data.get("status", None)
            contract_file = self.request.data.get("contract_file", None)
            if contract_file:
                contract_file = json.dumps(contract_file)
            social_security = self.request.data.get("social_security", None)
            home_addr = self.request.data.get("home_addr", None)
            dic = {"card_id": card_id, "t1_card_no": t1_card_no, "status": s,
                   "t1_card_file": t1_card_file, "t1_end_time": t1_end_time, "t2_card_no": t2_card_no,
                   "t2_card_file": t2_card_file, "t2_end_time": t2_end_time, "contract_start_time": contract_start_time,
                   "contract_end_time": contract_end_time, "company_id": company, "contract_file": contract_file,
                   "social_security": social_security, "home_addr": home_addr}
            data.update(dic)
        return general_json_response(status.HTTP_200_OK, ErrorCode.SUCCESS, data)


class AuthUserDetailView(WdRetrieveUpdateAPIView, WdDestroyAPIView):

    model = AuthUser
    serializer_class = AuthUserSerializer
    g_serializer_class = AuthUserListSerializer
    POST_DATA_ID_RESPONSE = True
    POST_DATA_RESPONSE = True

    def get_object(self):
        obj = super(AuthUserDetailView, self).get_object()
        if obj and obj.username == u'admin':
            obj = None
        return obj

    def delete_check_parameter(self, kwargs):
        code = super(AuthUserDetailView, self).delete_check_parameter(kwargs)
        if code:
            return code
        if self.get_object() and int(self.get_id()) == self.request.user.id:
            code = ErrorCode.CAN_NOT_DEL_SELF
        return code

    def post_check_parameter(self, kwargs):
        code = super(AuthUserDetailView, self).post_check_parameter(kwargs)
        if code != ErrorCode.SUCCESS:
            return code
        a = AuthUser.objects.filter(username=self.request.data.get("username")).exclude(id=self.get_id())
        if a:
            return ErrorCode.USER_ACCOUNT_EXISTS
        password = self.request.data.pop('pwd')
        if password:
            password = make_password(password)
            self.request.data.update({'password': password})
        phone = self.request.data.get('phone', None)
        if phone:
            b = phone_check(phone)
            if not b:
                return ErrorCode.WRONG_PHONE
            # r = r'^(13\d|14[5|7]|15\d|166|17[3|6|7]|18\d)\d{8}$'
            # phone_pattern = re.compile(r)
            # b = phone_pattern.match(phone)
            # if not b:
            #     return ErrorCode.USER_PHONE_USED_ERROR

        email = self.request.data.get('email', None)
        if email:
            r = r'[a-zA-Z0-9_-]+@[a-zA-Z0-9]+(\.[a-zA-Z0-9]+)$'
            email_pattern = re.compile(r)
            b = email_pattern.match(email)
            if not b:
                return ErrorCode.USER_EMAIL_USED_ERROR

        add_all = self.request.data.get("add_all", None)
        if add_all == 1:
            register_codes = ElevatorInfo.objects.filter_active().values_list("register_code", flat=True).distinct()
        else:
            register_codes = self.request.data.get("register_codes", [])
        aid = self.get_id()
        AuthUserElevatorRelation.objects.filter_active(auth_user_id=aid).update(is_active=False)
        lift = self.request.data.get("lift", None)
        print "lift: %s" % lift
        print type(lift)
        bulk_list = []
        if lift == "1":
            print "register_codes: %s" % register_codes
            data = query_elevators(register_codes)
            print "data: %s" % data
            for dic in data:
                bulk_list.append(AuthUserElevatorRelation(auth_user_id=aid, register_code=dic['register_code'],
                                                          is_business=False, internal_no=dic['internal_no'],
                                                          maintain_company_name=dic['maintain_company_name'],
                                                          property_company_name=dic['property_company_name']))
        else:
            print "lift not 1"
            es = ElevatorInfo.objects.filter_active(register_code__in=register_codes)
            for e in es:
                bulk_list.append(AuthUserElevatorRelation(auth_user_id=aid, register_code=e.register_code,
                                                          is_business=True, internal_no=e.internal_no,
                                                          maintain_company_name=e.maintain_company_name,
                                                          property_company_name=e.property_company_name, ))
        if bulk_list:
            AuthUserElevatorRelation.objects.bulk_create(bulk_list)

        # elevators = ElevatorInfo.objects.filter_active(register_code__in=register_codes)
        # for e in elevators:
        #     bulk_list.append(AuthUserElevatorRelation(auth_user_id=aid, register_code=e.register_code,
        #                                               internal_no=e.internal_no,
        #                                               maintain_company_name=e.maintain_company_name,
        #                                               property_company_name=e.property_company_name)
        #                      )
        # if bulk_list:
        #     AuthUserElevatorRelation.objects.bulk_create(bulk_list)

        # organization = self.request.data.get("organization", None)
        user = self.request.user
        role = self.request.data.get("role", None)
        if user.role == 0:
            self.request.data.pop("organization", None)
        elif user.role == 20:
            if role == 30:
                self.request.data.pop("organization", None)
        # if organization:
        #     if user.username == u"admin":
        #         if organization == -1:
        #             self.request.data.update({"organization": None, "permit_all": True})
        #         return ErrorCode.SUCCESS
        #     if user.permit_all:
        #         if organization == -1:
        #             self.request.data.update({"organization": None, "permit_all": True})
        #         return ErrorCode.SUCCESS
        #     if not user.organization:
        #         return ErrorCode.USER_ORGANIZATION_NOT_PERMIT
        #     permit = user.organization.children()
        #     if organization not in permit:
        #         return ErrorCode.USER_ORGANIZATION_NOT_PERMIT

        return ErrorCode.SUCCESS

    def perform_destroy(self, instance):
        instance.is_active = False
        auth_code = ''.join(random.sample(string.ascii_letters, 8))
        instance.username += u"--" + auth_code
        instance.save()

    def put(self, request, *args, **kwargs):
        role = self.request.data.get("role", None)
        if role == 10:
            auth_user_id = self.get_id()
            card_id = self.request.data.get("card_id", None)
            t1_card_no = self.request.data.get("t1_card_no", None)
            t1_card_file = self.request.data.get("t1_card_file", None)
            t1_end_time = self.request.data.get("t1_end_time", None)
            t2_card_no = self.request.data.get("t2_card_no", None)
            t2_card_file = self.request.data.get("t2_card_file", None)
            t2_end_time = self.request.data.get("t2_end_time", None)
            contract_start_time = self.request.data.get("contract_start_time", None)
            contract_end_time = self.request.data.get("contract_end_time", None)
            s = self.request.data.get("status", None)
            contract_file = self.request.data.get("contract_file", None)
            cf = contract_file
            if contract_file:
                contract_file = json.dumps(contract_file)
            social_security = self.request.data.get("social_security", None)
            home_addr = self.request.data.get("home_addr", None)
            dic = {"auth_user_id": auth_user_id, "card_id": card_id, "t1_card_no": t1_card_no, "status": s,
                   "t1_card_file": t1_card_file, "t1_end_time": t1_end_time, "t2_card_no": t2_card_no,
                   "t2_card_file": t2_card_file, "t2_end_time": t2_end_time, "contract_start_time": contract_start_time,
                   "contract_end_time": contract_end_time, "contract_file": contract_file,
                   "social_security": social_security, "home_addr": home_addr}
            Person.objects.update_or_create(auth_user_id=auth_user_id, defaults=dic)

            if self.p_serializer_class is not None:
                self.serializer_class = self.p_serializer_class
            if self.partial:
                rsp = self.partial_update(request, *args, **kwargs)
            else:
                rsp = self.update(request, *args, **kwargs)
            data = rsp.data
            data['contract_file'] = cf
            return general_json_response(status.HTTP_200_OK, ErrorCode.SUCCESS, data)
        return super(AuthUserDetailView, self).put(request, *args, **kwargs)


def get_tree(depth, l):

    while depth > 0:
        for j in l:
            if j['depth_id'] == depth - 1:
                for k in l:
                    if k['depth_id'] == depth and k['parent'] == j['id']:
                        j['list'].append(k)
                j['list'].sort(key=lambda x: x['serial_num'])
        depth -= 1
    if l:
        data = l[0]
    else:
        data = {}
    return data
        # if l:
        #     dic = {
        #         "name": name,
        #         "list": [l[0]],
        #         "id": l[0]['id']
        #     }
        #     m[0]['list'].append(dic)
        # return m


class OrgForAuthUserListView(WdListAPIView):

    def get(self, request, *args, **kwargs):
        user = self.request.user
        m = [{
            "name": u"梯联网平台",
            "list": [],
            "id": -1
        }]
        permit = []
        role_type = self.request.GET.get("role_type", None)
        # if org_type == "40":
        #     company_type = 400
        # elif org_type == "10":
        #     company_type = 100
        # elif org_type == "20":
        #     company_type = 100
        # elif org_type == "30":
        #     company_type = 300
        # else:
        #     company_type = None

        if user.role == 0:
            if role_type == "0":
                permit = [-1]
                return general_json_response(status.HTTP_200_OK, ErrorCode.SUCCESS, {"org": m, "permit": permit})
            elif role_type == "10":
                return general_json_response(status.HTTP_200_OK, ErrorCode.SUCCESS, {"org": [], "permit": permit})
            elif role_type == "20":
                l = CompanyInfo.objects.filter_active(company_type=100).values("id", "name")
                permit = [item['id'] for item in l]
                m[0]['list'] = l
                return general_json_response(status.HTTP_200_OK, ErrorCode.SUCCESS, {"org": m, "permit": permit})
            elif role_type == "30":
                l = CompanyInfo.objects.filter_active(company_type=300).values("id", "name")
                m[0]['list'] = l
                permit = [item['id'] for item in l]
                return general_json_response(status.HTTP_200_OK, ErrorCode.SUCCESS, {"org": m, "permit": permit})
            else:
                l = CompanyInfo.objects.filter_active(company_type=400).values("id", "name")
                m[0]['list'] = l
                permit = [item['id'] for item in l]
                return general_json_response(status.HTTP_200_OK, ErrorCode.SUCCESS, {"org": m, "permit": permit})
        elif user.role == 10:
            return general_json_response(status.HTTP_200_OK, ErrorCode.SUCCESS, {"org": [], "permit": permit})
        elif user.role == 20:
            cp = CompanyPerson.objects.filter_active(auth_user=user).first()
            company = cp.company
            if role_type in ("10", "20"):
                m[0]['list'] = [{"id": company.id, "name": company.name, "list": []}]
                organizations = Organization.objects.filter_active(company=company)
                l = OrganizationSerializer(instance=organizations, many=True).data
                depth = organizations.aggregate(Max("depth_id"))['depth_id__max']
                data = get_tree(depth, l)
                m[0]['list'][0]['list'] = [data]
                if cp.is_admin:
                    permit = organizations.values_list("id", flat=True).distinct()
                    return general_json_response(status.HTTP_200_OK, ErrorCode.SUCCESS, {"org": m, "permit": permit})
                else:
                    admin_role = user.admin_role
                    if admin_role:
                        oarr = OrganizationAdminRoRelation.objects.filter_active(admin_role=admin_role).first()
                        if oarr and oarr.organization:
                            permit = oarr.organization.children()
                            return general_json_response(status.HTTP_200_OK, ErrorCode.SUCCESS, {"org": m, "permit": permit})
                    return general_json_response(status.HTTP_200_OK, ErrorCode.SUCCESS, {"org": m, "permit": permit})
            elif role_type == "30":
                l = CompanyInfo.objects.filter_active(company_type=300, service_id=company.id).values("id", "name")
                print "l"
                print l
                m[0]['list'] = l
                permit = [item['id'] for item in l]
                return general_json_response(status.HTTP_200_OK, ErrorCode.SUCCESS, {"org": m, "permit": permit})
            else:
                return general_json_response(status.HTTP_200_OK, ErrorCode.SUCCESS, {"org": [], "permit": permit})
        elif user.role in (30, 40):
            cp = CompanyPerson.objects.filter_active(auth_user=user).first()
            company = cp.company
            m[0]['list'] = [{"id": company.id, "name": company.name, "list": []}]
            organizations = Organization.objects.filter_active(company=company)
            l = OrganizationSerializer(instance=organizations, many=True).data
            depth = organizations.aggregate(Max("depth_id"))['depth_id__max']
            data = get_tree(depth, l)
            if data:
                m[0]['list'][0]['list'] = [data]
            else:
                m[0]['list'][0]['list'] = []
            if cp.is_admin:
                permit = organizations.values_list("id", flat=True).distinct()
                return general_json_response(status.HTTP_200_OK, ErrorCode.SUCCESS, {"org": m, "permit": permit})
            else:
                admin_role = user.admin_role
                if admin_role:
                    oarr = OrganizationAdminRoRelation.objects.filter_active(admin_role=admin_role).first()
                    if oarr and oarr.organization:
                        permit = oarr.organization.children()
                        return general_json_response(status.HTTP_200_OK, ErrorCode.SUCCESS,
                                                     {"org": m, "permit": permit})
                return general_json_response(status.HTTP_200_OK, ErrorCode.SUCCESS, {"org": m, "permit": permit})

                # l = CompanyInfo.objects.filter_active(company_type=300, service_id=company.id).values("id", "name")
                # m[0]['list'] = l
                # permit = [item['id'] for item in l]
                # return general_json_response(status.HTTP_200_OK, ErrorCode.SUCCESS, {"org": m, "permit": permit})
        return general_json_response(status.HTTP_200_OK, ErrorCode.SUCCESS, {"org": [], "permit": permit})


        # if user.role == 0 or (user.role != 0 and user.company_person.is_admin):
        #     service_id = 0 if user.role == 0 else user.company_person.service_id
        #     permit = Organization.objects.filter_active(service_id=service_id).values_list("id", flat=True).distinct()
        #     ids = Organization.objects.filter_active(service_id=service_id, parent=None, company__is_active=True, company__company_type=company_type).values_list("company_id", flat=True).distinct()
        #     for i in ids:
        #         depth = Organization.objects.filter_active(company_id=i).aggregate(Max("depth_id"))[
        #             'depth_id__max']
        #         organization = Organization.objects.filter_active(company_id=i)
        #         l = OrganizationSerializer(instance=organization, many=True).data
        #         m = get_tree(m, depth, l, organization.first().name)
        # else:
        #     if user.organization and user.organization.is_active:
        #         if user.role in (0, 40):
        #             service_id = 0
        #         else:
        #             cp = CompanyPerson.objects.get(auth_user=user)
        #             service_id = cp.company.service_id
        #         permit = user.organization.children()
        #         if user.organization.company and user.organization.management.is_active:
        #             management_id = user.organization.management_id
        #             depth = Organization.objects.filter_active(management_id=management_id, service_id=service_id, management__org_type=int(org_type)).aggregate(Max("depth_id"))[
        #                 'depth_id__max']
        #             organization = Organization.objects.filter_active(management_id=management_id, service_id=service_id, management__org_type=int(org_type))
        #             if organization:
        #                 l = OrganizationSerializer(instance=organization, many=True).data
        #                 m = get_tree(m, depth, l, organization.first().name)
        # data = {"org": m, "permit": permit}
        # return general_json_response(status.HTTP_200_OK, ErrorCode.SUCCESS, data)


class ElevatorForAuthUserListView(WdListAPIView):
    model = ElevatorInfo
    serializer_class = ElevatorSerializer
    SEARCH_FIELDS_FOREACH = ("register_code", "internal_no", "maintain_company_name", "property_company_name")

    def qs_filter(self, qs):
        qs = super(ElevatorForAuthUserListView, self).qs_filter(qs)
        user = self.request.user
        if user.role == 0:
            pass
        elif user.role == 10:
            qs = qs.none()
        elif user.company_person.is_admin:
            pass
        else:
            r = user.elevators()
            qs = qs.filter(register_code__in=r)
        return qs

    def get(self, request, *args, **kwargs):
        lift = self.request.GET.get("lift", None)
        if lift == "1":
            register_code = self.request.GET.get("register_code", None)
            internal_no = self.request.GET.get("internal_no", None)
            property_company_name = self.request.GET.get("property_company_name", None)
            maintain_company_name = self.request.GET.get("maintain_company_name", None)
            page = self.request.GET.get("page", 1)
            page_size_count = self.request.GET.get("page_size_count", 8)
            total, data = get_elevators(register_code, internal_no, property_company_name, maintain_company_name, page,
                                        page_size_count)
            res = {"count": total, "results": data}
            response = general_json_response(status.HTTP_200_OK, ErrorCode.SUCCESS, res)
            return response
        try:
            response = super(WdListAPIView, self).get(request, *args, **kwargs)
        except NotFound, e:  # paginate_queryset raise NotFound
            return general_json_response(status.HTTP_200_OK, ErrorCode.SUCCESS, [])
        response = general_json_response(status.HTTP_200_OK, ErrorCode.SUCCESS, response.data)
        return response


    # # def qs_filter(self, qs):
    #     qs = super(ElevatorForAuthUserListView, self).qs_filter(qs)
        # oid = self.request.GET.get("organization", None)
        # if oid:
        #     rc = OrganizationElevatorRelation.objects.filter_active(organization_id=int(oid)).values_list("register_code", flat=True).distinct()
        #     qs = qs.filter(register_code__in=rc)
        # else:
        #     qs = qs.none()
        # return qs


# class OrganizationManagementListCreateView(WdListCreateAPIView):
#
#     model = OrganizationManagement
#     serializer_class = OrganizationManagementSerializer
#     SEARCH_FIELDS = ("name", )
#     FILTER_FIELDS = ("org_type", )


# class OrganizationManagementDetailView(WdRetrieveUpdateAPIView, WdDestroyAPIView):
#
#     model = OrganizationManagement
#     serializer_class = OrganizationManagementSerializer
#
#     def perform_destroy(self, instance):
#         super(OrganizationManagementDetailView, self).perform_destroy(instance)
#         Organization.objects.filter_active(management=self).update(is_active=False)


class OrganizationListCreateView(WdListCreateAPIView):

    model = Organization
    serializer_class = OrganizationSerializer
    POST_CHECK_REQUEST_PARAMETER = ("name", "serial_num", "company")

    def post_check_parameter(self, kwargs):
        code = super(OrganizationListCreateView, self).post_check_parameter(kwargs)
        if code != ErrorCode.SUCCESS:
            return code
        parent = self.request.data.get("parent", None)
        if parent:
            p = Organization.objects.get(id=parent)
            parent_name = p.name
            depth_id = p.depth_id + 1
        else:
            if Organization.objects.filter_active(company_id=self.request.data.get("company"), parent=None).exists():
                return ErrorCode.ORGANIZATION_EXISTED
            parent_name = None
            depth_id = 0
        self.request.data.update({"parent_name": parent_name, "depth_id": depth_id})
        return code

    # def qs_filter(self, qs):
    #     organization = self.request.GET.get("organization", None)
    #     if organization:
    #         organization = Organization.objects.get(id=int(organization))
    #         ids = organization.children()
    #         qs = qs.filter(id__in=ids)
    #     return qs

    def get(self, request, *args, **kwargs):
        company = self.request.GET.get("company", None)
        if not company:
            return general_json_response(status.HTTP_200_OK, ErrorCode.SUCCESS, {})
        flag = self.request.GET.get("flag", None)
        if flag == u"1":
            name = self.request.GET.get("key_words", None)
            if name:
                data = Organization.objects.filter_active(company_id=int(company), name__icontains=name).values("id", "name")
            else:
                data = Organization.objects.filter_active(company_id=int(company)).values("id", "name")
            return general_json_response(status.HTTP_200_OK, ErrorCode.SUCCESS, data)
        depth = Organization.objects.filter_active(company_id=int(company)).aggregate(Max("depth_id"))['depth_id__max']
        organization = Organization.objects.filter_active(company_id=int(company))
        l = OrganizationSerializer(instance=organization, many=True).data
        while depth > 0:
            for j in l:
                if j['depth_id'] == depth - 1:
                    for k in l:
                        if k['depth_id'] == depth and k['parent'] == j['id']:
                            j['list'].append(k)
                    j['list'].sort(key=lambda x: x['serial_num'])
            depth -= 1
        return general_json_response(status.HTTP_200_OK, ErrorCode.SUCCESS, l[0] if l else {})


class OrganizationDetailView(WdRetrieveUpdateAPIView, WdDestroyAPIView):

    model = Organization
    serializer_class = OrganizationSerializer
    POST_DATA_RESPONSE = True
    POST_DATA_ID_RESPONSE = True

    def post_check_parameter(self, kwargs):
        code = super(OrganizationDetailView, self).post_check_parameter(kwargs)
        if code != ErrorCode.SUCCESS:
            return code
        self.request.data.pop("parent_name", None)
        self.request.data.pop("parent", None)
        self.request.data.pop("depth_id", None)
        self.request.data.pop("company", None)
        self.request.data.pop("depth_id", None)
        self.request.data.pop("service_id", None)
        return code

    # def perform_destroy(self, instance):
    #     super(OrganizationDetailView, self).perform_destroy(instance)
    #     Organization.objects.filter_active(id__in=instance.children()).update(is_active=False)
    #     OrganizationElevatorRelation.objects.filter_active(organization_id__in=instance.children()).update(is_active=False)


class OrganizationElevatorRelationView(WdListCreateAPIView, WdDestroyAPIView):

    model = OrganizationElevatorRelation
    serializer_class = OrganizationElevatorRelationSerializer
    POST_CHECK_REQUEST_PARAMETER = ("organization", "register_codes")
    FILTER_FIELDS = ("organization", )
    SEARCH_FIELDS_FOREACH = ("register_code", "internal_no", "maintain_company_name", "property_company_name")

    def qs_filter(self, qs):
        qs = super(OrganizationElevatorRelationView, self).qs_filter(qs)
        basic = self.request.GET.get("basic", None)
        if basic == "1":
            qs = qs.filter(is_business=False)
        else:
            qs = qs.filter(is_business=True)
        return qs

    def post(self, request, *args, **kwargs):
        add_all = self.request.data.get("add_all", None)
        organization = self.request.data.get("organization")
        user = self.request.user
        lift = self.request.data.get("lift", None)
        register_codes = self.request.data.get("register_codes", [])
        buck_list = []

        if lift != "1":
            if add_all == 1:
                if user.role in (0, 40):
                    register_codes = ElevatorInfo.objects.filter_active().values_list("register_code", flat=True).distinct()
                else:
                    service_id = user.company_person.service_id
                    register_codes = ElevatorInfo.objects.filter_active(service_id=service_id).values_list("register_code", flat=True).distinct()
            rc = OrganizationElevatorRelation.objects.filter_active(organization_id=int(organization)).values_list("register_code", flat=True).distinct()
            register_codes = [i for i in register_codes if i not in rc]
            elevators = ElevatorInfo.objects.filter_active(register_code__in=register_codes)
            for e in elevators:
                service_id = 0 if user.role in (0, 40) else e.service_id
                buck_list.append(OrganizationElevatorRelation(organization_id=int(organization), register_code=e.register_code,
                                                              internal_no=e.internal_no,
                                                              maintain_company_name=e.maintain_company_name,
                                                              property_company_name=e.property_company_name,
                                                              service_id=service_id, is_business=True))
            print "not lift"

        else:
            sql = "select li.EQULOGCODE as register_code, li.EQUORGNO as internal_no, li.USEORGNAME as property_company_name, lei.MAIORGNAME as maintain_company_name from lift_info li left join lift_extinfo lei on li.EQUDATASYSID = lei.EQUDATASYSID"
            data = []
            if not add_all:
                print register_codes
                # sql += " where li.EQULOGCODE in ("
                # for i in register_codes:
                #     sql += i + ","
                # sql += ")"
                if register_codes:
                    sql += " where li.EQULOGCODE in ("
                    for i in register_codes:
                        sql += "'" + i + "',"
                    sql = sql.rstrip(",")
                    sql += ")"
                else:
                    sql += " where 1 > 1"
            try:
                print sql
                connect = mysql_singleton.MySQLSingle().get_conn()
                cursor = connect.cursor()
                cursor.execute(sql)
                data = cursor.fetchall()
                cursor.close()
                connect.close()
            except Exception as e:
                print e
            service_id = user.company_person.service_id if user.role != 0 else 0
            print "bulk_list length"
            for dic in data:
                buck_list.append(
                    OrganizationElevatorRelation(organization_id=int(organization), register_code=dic['register_code'],
                                                 internal_no=dic['internal_no'],
                                                 maintain_company_name=dic['maintain_company_name'],
                                                 property_company_name=dic['property_company_name'],
                                                 service_id=service_id, is_business=False))

            print len(buck_list)
        if buck_list:
            OrganizationElevatorRelation.objects.bulk_create(buck_list)
        return general_json_response(status.HTTP_200_OK, ErrorCode.SUCCESS)

    # def qs_filter(self, qs):
    #     organization = self.request.GET.get("organization", None)
    #     if qs:
    #         qs = qs.filter(organization_id=int(organization))
    #     return qs

    def delete(self, request, *args, **kwargs):
        register_codes = self.request.data.get("register_codes")
        organization = self.request.data.get("organization")
        OrganizationElevatorRelation.objects.filter_active(organization_id=int(organization), register_code__in=register_codes).\
            update(is_active=False)
        return general_json_response(status.HTTP_200_OK, ErrorCode.SUCCESS)


class ElevatorForOrgView(WdListAPIView):

    model = ElevatorInfo
    serializer_class = ElevatorSerializer
    SEARCH_FIELDS_FOREACH = ("register_code", "internal_no", "maintain_company_name", "property_company_name")

    def qs_filter(self, qs):
        organization = self.request.GET.get("organization", None)
        organization = Organization.objects.get(id=int(organization))
        if organization.parent:
            register_codes = OrganizationElevatorRelation.objects.filter_active(organization_id=organization.parent.id).values_list("register_code", flat=True).distinct()
            qs = qs.filter(register_code__in=register_codes)
        return qs

    def get(self, request, *args, **kwargs):
        lift = self.request.GET.get("lift", None)
        if lift:
            # try:
            #     connect = mysql_singleton.MySQLSingle().get_conn()
            #     cursor = connect.cursor()
            #     sql_total = "select count(1) as total from lift_info"
            #     cursor.execute(sql_total)
            #     total = cursor.fetchone()['total']
            #     sql = "select li.EQULOGCODE as register_code, li.EQUORGNO as internal_no, li.USEORGNAME as property_company_name, lei.MAIORGNAME as maintain_company_name from lift_info li left join lift_extinfo lei on li.EQUDATASYSID = lei.EQUDATASYSID"
            #     page = self.request.GET.get("page", 1)
            #     page_size_count = self.request.GET.get("page_size_count", 8)
            #     key_words = self.request.GET.get("key_words", None)
            #     start = (int(page) - 1) * int(page_size_count)
            #     if key_words:
            #         sql = sql + " where li.EQULOGCODE like '%" + key_words + "%' or li.EQUORGNO like '%" +key_words + \
            #               "%' or li.USEORGNAME like '%" + key_words + "%' or lei.MAIORGNAME like '%" + \
            #               key_words + "%'"
            #     sql = sql + " limit %s, %s" % (start, page_size_count)
            #     cursor.execute(sql)
            #     data = cursor.fetchall()
            #     connect.close()
            #     cursor.close()
            # except Exception as e:
            #     data = None
            #     total = 0
            #     print e
# def get_elevators(register_code, internal_no, property_company_name, maintain_company_name, page=1, page_size_count=8,):
            register_code = self.request.GET.get("register_code", None)
            internal_no = self.request.GET.get("internal_no", None)
            property_company_name = self.request.GET.get("property_company_name", None)
            maintain_company_name = self.request.GET.get("maintain_company_name", None)
            page = self.request.GET.get("page", 1)
            page_size_count = self.request.GET.get("page_size_count", 8)
            total, data = get_elevators(register_code, internal_no, property_company_name, maintain_company_name, page, page_size_count)
            res = {"count": total, "results": data}
            response = general_json_response(status.HTTP_200_OK, ErrorCode.SUCCESS, res)
            return response
        try:
            response = super(WdListAPIView, self).get(request, *args, **kwargs)
        except NotFound, e: # paginate_queryset raise NotFound
            return general_json_response(status.HTTP_200_OK, ErrorCode.SUCCESS, [])
        response = general_json_response(status.HTTP_200_OK, ErrorCode.SUCCESS, response.data)
        return response


class WorkHourPriceView(WdAPIView):

    def get(self, request, *args, **kwargs):
        user = self.request.user
        can_be_modify = False
        if user.role == 20 and user.company_person.is_admin:
            can_be_modify = True
        if user.role in (20, 30):
            service_id = user.company_person.service_id
            com = CompanyInfo.objects.get(id=service_id)
            hour_price = com.hour_price
        else:
            hour_price = 0
        data = {"can_be_modify": can_be_modify, "hour_price": hour_price}
        return general_json_response(status.HTTP_200_OK, ErrorCode.SUCCESS, data)

    def post(self, request, *args, **kwargs):
        user = self.request.user
        if user.role != 20 or not user.company_person.is_admin:
            return general_json_response(status.HTTP_200_OK, ErrorCode.PERMISSION_FAIL)

        service_id = user.company_person.service_id
        com = CompanyInfo.objects.get(id=service_id)
        hour_price = self.request.data.get("hour_price", 0)
        com.hour_price = hour_price
        com.save()
        return general_json_response(status.HTTP_200_OK, ErrorCode.SUCCESS)


class UploadFileView(WdAPIView):

    def post(self, request):
        update_by = self.request.user.id
        li = ['person', 'contract', 'elevator', 'task', 'wb_company', 'use_company']
        files = request.FILES
        file_type = files.keys()[0]
        dic = {}
        if file_type in li:
            file_obj = request.FILES.get(file_type, None)
            import time
            l = file_obj.name.rsplit('.', 1)
            if len(l) < 2:
                pass
            file_name = unicode(int(time.time() * 1000)) + u'.' + l[1]
            file_name = '%s/%s' % (settings.MEDIA_ROOT, file_name)
            with open(file_name, 'wb+') as f:
                for chunk in file_obj.chunks():
                    f.write(chunk)
            path = os.path.abspath(file_name)
            dic[file_type] = path
            res = data_import(dic, update_by)
            return general_json_response(status.HTTP_200_OK, ErrorCode.SUCCESS, res)
        return general_json_response(status.HTTP_200_OK, ErrorCode.FAILURE, u"请核实上传参数")

    #
    # file = request.FILES.get("upfile", None)
    #     l = file.name.rsplit('.', 1)
    #     if len(l) < 2:
    #         pass
    #     file_name = l[0] + unicode(int(time.time())) + u'.' + l[1]
    #     file_name = '%s/%s' % (settings.MEDIA_ROOT, file_name)
    #     with open(file_name, 'wb+') as f:
    #         for chunk in file.chunks():
    #             f.write(chunk)
    #     down_load_path = settings.DOMAIN_NAME + '/uploaded/' + os.path.basename(file_name)
    #     return general_json_response(status.HTTP_200_OK, ErrorCode.SUCCESS, down_load_path)
    #


class InfoCountListView(WdListAPIView):
    def get(self, request, *args, **kwargs):
        elevator_nums = list()
        recent_elevator = list()
        person_nums = list()
        recent_person = list()
        contract_nums = list()
        recent_contract = list()
        property_nums = list()
        recent_property = list()
        person_bind_nums = list()
        recent_person_bind = list()
        recent_date = list()
        data = dict()
        registry = dict()
        user = self.request.user
        current_date = datetime.now()
        if user.role == 0:
            maintain_nums = list()
            recent_maintain = list()
            elevator_count = ElevatorInfo.objects.filter_active().count()
            maintain_company_count = CompanyInfo.objects.filter_active(company_type=100).count()
            property_company_count = CompanyInfo.objects.filter_active(company_type=300).count()
            maintain_person_count = Person.objects.filter_active().count()
            contract_count = Contract.objects.filter_active().count()
            person_bind_count = ElevatorInfo.objects.filter_active(registry_status=20).count()

            # 获取备案信息
            elevator_w = ElevatorInfo.objects.filter_active(registry_status=10).count()
            elevator_t = ElevatorInfo.objects.filter_active(registry_status=20).count()
            elevator_f = ElevatorInfo.objects.filter_active(registry_status=30).count()
            maintain_company_w = CompanyInfo.objects.filter_active(registry_status=10, company_type=100).count()
            maintain_company_t = CompanyInfo.objects.filter_active(registry_status=20).count()
            maintain_company_f = CompanyInfo.objects.filter_active(registry_status=30).count()
            person_w = Person.objects.filter_active(registry_status=10).count()
            person_t = Person.objects.filter_active(registry_status=20).count()
            person_f = Person.objects.filter_active(registry_status=30).count()
            contract_w = Contract.objects.filter_active(registry_status=10).count()
            contract_t = Contract.objects.filter_active(registry_status=20).count()
            contract_f = Contract.objects.filter_active(registry_status=30).count()
            person_bind_w = ElevatorInfo.objects.filter_active(registry_status=20, is_binded=10).count()
            person_bind_t = ElevatorInfo.objects.filter_active(registry_status=20, is_binded=20).count()
            person_bind_f = ElevatorInfo.objects.filter_active(registry_status=20, is_binded=30).count()
            registry['elevator_w'] = elevator_w
            registry['elevator_t'] = elevator_t
            registry['elevator_f'] = elevator_f
            registry['maintain_company_w'] = maintain_company_w
            registry['maintain_company_t'] = maintain_company_t
            registry['maintain_company_f'] = maintain_company_f
            registry['person_w'] = person_w
            registry['person_t'] = person_t
            registry['person_f'] = person_f
            registry['contract_w'] = contract_w
            registry['contract_t'] = contract_t
            registry['contract_f'] = contract_f
            registry['person_bind_w'] = person_bind_w
            registry['person_bind_t'] = person_bind_t
            registry['person_bind_f'] = person_bind_f
            data['elevator_count'] = elevator_count
            data['maintain_company_count'] = maintain_company_count
            data['property_company_count'] = property_company_count
            data['maintain_person_count'] = maintain_person_count
            data['contract_count'] = contract_count
            data['person_bind_count'] = person_bind_count
            data['registry'] = registry

            # 获取最近七天电梯的数量
            for i in range(7):
                now_date = (current_date - timedelta(days=i))
                recent_date.append(now_date.strftime("%Y-%m-%d"))
                next_date = (now_date + timedelta(days=1)).strftime("%Y-%m-%d")
                if self.request.GET.get('key_words'):
                    maintain_company_name = self.request.GET.get('key_words', None)
                    try:
                        company_obj = CompanyInfo.objects.filter_active(name=maintain_company_name).first()
                    except Exception as e:
                        print e
                        return general_json_response(status.HTTP_200_OK, ErrorCode.USER_ACCOUNT_NOT_EXISTS)
                    auth_user_id = user.id
                    company_id = company_obj.id

                    nums_e = ElevatorInfo.objects.filter_active(update_time__lte=next_date,
                                                                maintain_company=company_id).count()
                    nums_p = Person.objects.filter_active(update_time__lte=next_date, company=company_id).count()
                    nums_c = Contract.objects.filter_active(update_time__lte=next_date,
                                                            maintain_company=company_id).count()
                    nums_u = CompanyInfo.objects.filter_active(update_time__lte=next_date, company_type=300,
                                                               service_id=company_id).count()
                    nums_t = CompanyInfo.objects.filter_active(update_time__lte=next_date, company_type=100).count()

                    nums_b = ElevatorInfo.objects.filter_active(update_time__lte=next_date, registry_status=20,
                                                                maintain_company=company_id).\
                        exclude(is_binded=10).count()

                    elevator_num = ElevatorInfo.objects.filter_active(maintain_company=company_id).count()
                    property_company_num = CompanyInfo.objects.filter_active(service_id=company_id,
                                                                             company_type=300).count()
                    maintain_person_num = Person.objects.filter_active(company=company_id).count()
                    contract_num = Contract.objects.filter_active(maintain_company=company_id).count()
                    person_bind_num = ElevatorInfo.objects.filter_active(registry_status=20,
                                                                         maintain_company=company_id).count()

                    elevator_w_g = ElevatorInfo.objects.filter_active(registry_status=10, maintain_company=company_id).count()
                    elevator_t_g = ElevatorInfo.objects.filter_active(registry_status=20, maintain_company=company_id).count()
                    elevator_f_g = ElevatorInfo.objects.filter_active(registry_status=30, maintain_company=company_id).count()
                    person_w_g = Person.objects.filter_active(registry_status=10, company=company_id).count()
                    person_t_g = Person.objects.filter_active(registry_status=20, company=company_id).count()
                    person_f_g = Person.objects.filter_active(registry_status=30, company=company_id).count()
                    contract_w_g = Contract.objects.filter_active(registry_status=10, maintain_company=company_id).count()
                    contract_t_g = Contract.objects.filter_active(registry_status=20, maintain_company=company_id).count()
                    contract_f_g = Contract.objects.filter_active(registry_status=30, maintain_company=company_id).count()
                    person_bind_w = ElevatorInfo.objects.filter_active(registry_status=20, is_binded=10,
                                                                       maintain_company=company_id).count()
                    person_bind_t = ElevatorInfo.objects.filter_active(registry_status=20, is_binded=20,
                                                                       maintain_company=company_id).count()
                    person_bind_f = ElevatorInfo.objects.filter_active(registry_status=20, is_binded=30,
                                                                       maintain_company=company_id).count()
                    registry['elevator_w_g'] = elevator_w_g
                    registry['elevator_t_g'] = elevator_t_g
                    registry['elevator_f_g'] = elevator_f_g
                    registry['person_w_g'] = person_w_g
                    registry['person_t_g'] = person_t_g
                    registry['person_f_g'] = person_f_g
                    registry['contract_w_g'] = contract_w_g
                    registry['contract_t_g'] = contract_t_g
                    registry['contract_f_g'] = contract_f_g
                    registry['person_bind_w'] = person_bind_w
                    registry['person_bind_t'] = person_bind_t
                    registry['person_bind_f'] = person_bind_f
                    data['elevator_num'] = elevator_num
                    data['property_company_num'] = property_company_num
                    data['maintain_person_num'] = maintain_person_num
                    data['contract_num'] = contract_num
                    data['person_bind_num'] = person_bind_num
                    data['maintain_num'] = 1
                    data['registry'] = registry
                else:
                    nums_e = ElevatorInfo.objects.filter_active(update_time__lte=next_date).count()
                    nums_p = Person.objects.filter_active(update_time__lte=next_date).count()
                    nums_c = Contract.objects.filter_active(update_time__lte=next_date).count()
                    nums_u = CompanyInfo.objects.filter_active(update_time__lte=next_date, company_type=300).count()
                    nums_t = CompanyInfo.objects.filter_active(update_time__lte=next_date, company_type=100).count()
                    nums_b = ElevatorInfo.objects.filter_active(update_time__lte=next_date, registry_status=20).\
                        exclude(is_binded=10).count()
                elevator_nums.append(nums_e)
                person_nums.append(nums_p)
                contract_nums.append(nums_c)
                property_nums.append(nums_u)
                maintain_nums.append(nums_t)
                person_bind_nums.append(nums_b)

            recent_e = dict(zip(recent_date, elevator_nums))
            sorted_recent_e = sorted(recent_e.items(), key=operator.itemgetter(0))
            for item in sorted_recent_e:
                recent_elevator.append(list(item))
            data['recent_elevator'] = recent_elevator

            recent_p = dict(zip(recent_date, person_nums))
            sorted_recent_p = sorted(recent_p.items(), key=operator.itemgetter(0))
            for item in sorted_recent_p:
                recent_person.append(list(item))
            data['recent_person'] = recent_person

            recent_c = dict(zip(recent_date, contract_nums))
            sorted_recent_c = sorted(recent_c.items(), key=operator.itemgetter(0))
            for item in sorted_recent_c:
                recent_contract.append(list(item))
            data['recent_contract'] = recent_contract

            recent_u = dict(zip(recent_date, property_nums))
            sorted_recent_u = sorted(recent_u.items(), key=operator.itemgetter(0))
            for item in sorted_recent_u:
                recent_property.append(list(item))
            data['recent_property'] = recent_property

            recent_m = dict(zip(recent_date, maintain_nums))
            sorted_recent_m = sorted(recent_m.items(), key=operator.itemgetter(0))
            for item in sorted_recent_m:
                recent_maintain.append(list(item))
            data['recent_maintain'] = recent_maintain

            recent_b = dict(zip(recent_date, person_bind_nums))
            sorted_recent_b = sorted(recent_b.items(), key=operator.itemgetter(0))
            for item in sorted_recent_b:
                recent_person_bind.append(list(item))
            data['recent_person_bind'] = recent_person_bind
            return general_json_response(status.HTTP_200_OK, ErrorCode.SUCCESS, data)
        elif user.role == 20:
            auth_user_id = user.id
            maintain_company_obj = CompanyPerson.objects.filter_active(auth_user=auth_user_id).first().company
            company_id = maintain_company_obj.id

            elevator_num = ElevatorInfo.objects.filter_active(maintain_company=company_id).count()
            property_company_num = CompanyInfo.objects.filter_active(service_id=company_id, company_type=300).count()
            maintain_person_num = Person.objects.filter_active(company=company_id).count()
            contract_num = Contract.objects.filter_active(maintain_company=company_id).count()
            person_bind_num = ElevatorInfo.objects.filter_active(maintain_company=company_id, registry_status=20).count()





            # 备案数据
            elevator_w_g = ElevatorInfo.objects.filter_active(registry_status=10, maintain_company=company_id).count()
            elevator_t_g = ElevatorInfo.objects.filter_active(registry_status=20, maintain_company=company_id).count()
            elevator_f_g = ElevatorInfo.objects.filter_active(registry_status=30, maintain_company=company_id).count()
            person_w_g = Person.objects.filter_active(registry_status=10, company=company_id).count()
            person_t_g = Person.objects.filter_active(registry_status=20, company=company_id).count()
            person_f_g = Person.objects.filter_active(registry_status=30, company=company_id).count()
            contract_w_g = Contract.objects.filter_active(registry_status=10, maintain_company=company_id).count()
            contract_t_g = Contract.objects.filter_active(registry_status=20, maintain_company=company_id).count()
            contract_f_g = Contract.objects.filter_active(registry_status=30, maintain_company=company_id).count()
            person_bind_w = ElevatorInfo.objects.filter_active(registry_status=20, is_binded=10,
                                                               maintain_company=company_id).count()
            person_bind_t = ElevatorInfo.objects.filter_active(registry_status=20, is_binded=20,
                                                               maintain_company=company_id).count()
            person_bind_f = ElevatorInfo.objects.filter_active(registry_status=20, is_binded=30,
                                                               maintain_company=company_id).count()
            registry['elevator_w_g'] = elevator_w_g
            registry['elevator_t_g'] = elevator_t_g
            registry['elevator_f_g'] = elevator_f_g
            registry['person_w_g'] = person_w_g
            registry['person_t_g'] = person_t_g
            registry['person_f_g'] = person_f_g
            registry['contract_w_g'] = contract_w_g
            registry['contract_t_g'] = contract_t_g
            registry['contract_f_g'] = contract_f_g
            registry['person_bind_w'] = person_bind_w
            registry['person_bind_t'] = person_bind_t
            registry['person_bind_f'] = person_bind_f
            data['elevator_num'] = elevator_num
            data['property_company_num'] = property_company_num
            data['maintain_person_num'] = maintain_person_num
            data['contract_num'] = contract_num
            data['person_bind_num'] = person_bind_num
            data['registry'] = registry
            # 电梯7天数据
            elevator_nums = list()
            recent_date = list()
            current_date = datetime.now()
            for i in range(7):
                now_date = (current_date - timedelta(days=i))
                recent_date.append(now_date.strftime("%Y-%m-%d"))
                next_date = (now_date + timedelta(days=1)).strftime("%Y-%m-%d")
                nums_e = ElevatorInfo.objects.filter_active(update_time__lte=next_date,
                                                            maintain_company=company_id).count()
                nums_p = Person.objects.filter_active(update_time__lte=next_date,
                                                      company=company_id).count()
                nums_c = Contract.objects.filter_active(update_time__lte=next_date,
                                                        maintain_company=company_id).count()
                nums_u = CompanyInfo.objects.filter_active(update_time__lte=next_date,
                                                           company_type=300,
                                                           service_id=company_id).count()
                nums_b = ElevatorInfo.objects.filter_active(update_time__lte=next_date, registry_status=20,
                                                            maintain_company=company_id).exclude(is_binded=10).count()
                elevator_nums.append(nums_e)
                person_nums.append(nums_p)
                contract_nums.append(nums_c)
                property_nums.append(nums_u)
                person_bind_nums.append(nums_b)

            recent_e = dict(zip(recent_date, elevator_nums))
            sorted_recent_e = sorted(recent_e.items(), key=operator.itemgetter(0))
            for item in sorted_recent_e:
                recent_elevator.append(list(item))
            data['recent_elevator'] = recent_elevator

            recent_p = dict(zip(recent_date, person_nums))
            sorted_recent_p = sorted(recent_p.items(), key=operator.itemgetter(0))
            for item in sorted_recent_p:
                recent_person.append(list(item))
            data['recent_person'] = recent_person

            recent_c = dict(zip(recent_date, contract_nums))
            sorted_recent_c = sorted(recent_c.items(), key=operator.itemgetter(0))
            for item in sorted_recent_c:
                recent_contract.append(list(item))
            data['recent_contract'] = recent_contract

            recent_u = dict(zip(recent_date, property_nums))
            sorted_recent_u = sorted(recent_u.items(), key=operator.itemgetter(0))
            for item in sorted_recent_u:
                recent_property.append(list(item))
            data['recent_property'] = recent_property

            recent_b = dict(zip(recent_date, person_bind_nums))
            sorted_recent_b = sorted(recent_b.items(), key=operator.itemgetter(0))
            for item in sorted_recent_b:
                recent_person_bind.append(list(item))
            data['recent_person_bind'] = recent_person_bind
            return general_json_response(status.HTTP_200_OK, ErrorCode.SUCCESS, data)
        return general_json_response(status.HTTP_200_OK, ErrorCode.SUCCESS, data)


class LogRefreshView(WdAPIView):
    def get(self, request, *args, **kwargs):
        service_id = self.request.user.service_id
        log_refresh = LogRefresh.objects.filter_active(service_id=service_id).first()
        ref = 0
        if log_refresh and log_refresh.refresh:
            ref = 1
        return general_json_response(status.HTTP_200_OK, ErrorCode.SUCCESS, {"refresh": ref})

    def post(self, request, *args, **kwargs):
        refresh = self.request.data.get("refresh", 0)
        refresh = True if refresh else False
        service_id = self.request.user.service_id
        LogRefresh.objects.update_or_create(service_id=service_id, defaults={"refresh": refresh})
        return general_json_response(status.HTTP_200_OK, ErrorCode.SUCCESS)


class SystemLogView(WdListAPIView, WdDestroyAPIView):

    model = SystemLog
    serializer_class = SystemLogSerializer
    SEARCH_FIELDS = ("log", )
    FILTER_FIELDS = ("log_type", )

    def qs_filter(self, qs):
        qs = super(SystemLogView, self).qs_filter(qs)
        time_from = self.request.GET.get("time_from", None)
        time_to = self.request.GET.get("time_to", None)
        if time_from:
            qs = qs.filter(create_time__gte=time_from)
        if time_to:
            qs = qs.filter(create_time__lte=time_to)
        return qs

    def delete(self, request, *args, **kwargs):
        log_type = self.request.data.get("log_type", None)
        SystemLog.objects.filter(log_type=log_type).delete()
        return general_json_response(status.HTTP_200_OK, ErrorCode.SUCCESS)


post_save.connect(receiver=company_registry, sender=CompanyInfo)
post_save.connect(receiver=company_registry, sender=Person)
post_save.connect(receiver=company_registry, sender=ElevatorInfo)
post_save.connect(receiver=company_registry, sender=Contract)
post_delete.connect(receiver=elevator_delete, sender=ElevatorInfo)
















